Podręcznik PHP

Opracowany przez:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
2012-03-23
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 - 2012 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, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yannick Torres, 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, IIS, and many others. And this includes any web server that can utilize the FastCGI PHP binary, like lighttpd and nginx. PHP works as either a module, or 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 (OOP), or a mixture of them both.

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 using one of the database specific extensions (e.g., for mysql), or using an abstraction layer like PDO, or connect to any database supporting the Open Database Connection standard via the ODBC extension. Other databases may utilize cURL or sockets, like CouchDB.

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.

PHP has useful text processing features, which includes the Perl compatible regular expressions (PCRE), and many extensions and tools to parse and access XML documents. PHP standardizes all of the XML extensions on the solid base of libxml2, and extends the feature set adding SimpleXML, XMLReader and XMLWriter support.

And many other interesting extensions exist, which are categorized both alphabetically and by category. And there are additional PECL extensions that may or may not be documented within the PHP manual itself, like » XDebug.

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). If 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
  • A web server
  • Any module specific components (such as GD, PDF libs, etc.)

When building directly from SVN sources or after custom modifications you might also need:

  • autoconf: 2.13+ (for PHP < 5.4.0), 2.59+ (for PHP >= 5.4.0)
  • automake: 1.4+
  • libtool: 1.4.x+ (except 1.4.2)
  • re2c: Version 0.13.4 or newer
  • flex: Version 2.5.4 (for PHP <= 5.2)
  • bison: Version 1.28 (preferred), 1.35, or 1.75

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.

      LoadModule php5_module libexec/libphp5.so
      
15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:
    
      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

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 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 libphp5.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. 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, który jest domyślny w Apache 2.0 i Apache 2.2. 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.

The most recent 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.

  1. Obtain the Apache HTTP server from the location listed above, and unpack it:

    gzip -d httpd-2_x_NN.tar.gz
    tar -xf httpd-2_x_NN.tar
    
  2. Likewise, obtain and unpack the PHP source:

    gunzip php-NN.tar.gz
    tar -xf php-NN.tar
    
  3. Build and install Apache. Consult the Apache install documentation for more details on building Apache.

    cd httpd-2_x_NN
    ./configure --enable-so
    make
    make install
    
  4. 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
    

  5. Now, configure and build PHP. This is where you customize PHP with various options, like which extensions will be enabled. Run ./configure --help for a list of available options. In our example we'll do a simple configure with Apache 2 and MySQL support.

    If you built Apache from source, as described above, the below example will match your path for apxs, but if you installed Apache some other way, you'll need to adjust the path to apxs accordingly. Note that some distros may rename apxs to apxs2.

    cd ../php-NN
    ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql
    make
    make install
    

    If you decide to change your configure options after installation, you'll need to re-run the configure, make, and make install 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.

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

    If you instead choose php.ini-production, be certain to read the list of changes within, as they affect how PHP behaves.

  7. 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
  8. 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 .php 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.

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


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

By default, PHP is built as both a CLI and CGI program, which can be used for CGI processing. If you are running a web server that 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.

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.

For unpacking the PHP distribution you need

  • tar
  • gzip or
  • bzip2

For compiling PHP you need

  • gcc (recommended, other C compilers may work)
  • make
  • GNU sed

For building extra extensions or hacking the code of PHP you might also need

  • flex (up to PHP 5.2)
  • re2c
  • bison
  • m4
  • autoconf
  • automake
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. The Image Packaging System (IPS) for Solaris 11 Express also contains most of the required components for installation using the pkg command.



Debian GNU/Linux installation notes

This section contains notes and hints specific to installing PHP on » Debian GNU/Linux.

Ostrzeżenie

Unofficial builds from third-parties are not supported here. Any bugs should be reported to the Debian team unless they can be reproduced using the latest builds from our » download area.

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. PHP is bundled with Macs, and compiling is similar to the Unix installation guide.


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 PHP on Mac OS X

Use the Unix installation guide to compile PHP on Mac OS X.




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.

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 a development environment such as 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 option for the feature "PDO" you will install all PDO Drivers).

Ostrzeżenie

It is not recommended to install all extensions by default, since many of 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 IIS7 or greater and PHP 5.3+, then the VC9 binaries of PHP should be used.

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



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

Anonymous authenication for IIS 5.1 and IIS 6.0

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

Setting index.php as default document for IIS

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.

Enabling FastCGI support for IIS7 on Windows Vista SP1 and Windows 7

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.

Enabling FastCGI support on Windows Server 2008 and Windows Server 2008 R2

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;

    Create IIS handler mapping for PHP : Locate Handler Mappings

  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.

Create IIS handler mapping for PHP : Add Handler Mapping

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

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 timeout settings

%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 powinny 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.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.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 Support

Users of Apache 2.2 should note that the DLL file for Apache 2.2 is named php5apache2_2.dll rather than php5apache2.dll and is available only for PHP 5.2.0 and later. See also » http://snaps.php.net/

You are strongly encouraged to consult the » Apache Documentation to get a basic understanding of the Apache 2.x Server. Also consider reading the » Windows specific notes for Apache 2.x before reading on here.

Apache 2.x is designed to run on the Windows version designated as server platforms, such as Windows NT 4.0, Windows 2000, Windows XP, or Windows 7. While Apache 2.x works tolerably well on Windows 9x, support on these platforms is incomplete, and some things will not work correctly. There is no plan to remedy this situation.

Download the most recent version of »  Apache 2.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 three ways to set up PHP to work with Apache 2.x on Windows. You can run PHP as a handler, as a CGI, or under FastCGI.

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 powinny 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 handler

You need to insert the following lines into your Apache httpd.conf configuration file to load the PHP module for Apache 2.x:

Przykład #1 PHP and Apache 2.x as handler

# 
LoadModule php5_module "c:/php/php5apache2.dll"
AddHandler 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 php5apache2.dll or php5apache2_2.dll in your LoadModule directive and verify that the referenced file is in fact located at the file path that you point to in this directive.

The above configuration will enable PHP handling of any file that has a .php extension, even if there are other file extensions. For example, a file named example.php.txt will be executed by the PHP handler. To ensure that only files that end in .php are executed, use the following configuration instead:

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

Running PHP as CGI

You should consult the » Apache CGI documentation for a more complete understanding of running CGI on Apache.

To run PHP as CGI, you'll need to place your php-cgi files in a directory designated as a CGI directory using the ScriptAlias directive.

You will then need to insert a #! line in the PHP files, pointing to the location of your PHP binary:

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

#!C:/php/php.exe
<?php
  phpinfo();
?>

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.

Running PHP under FastCGI

Running PHP under FastCGI has a number of advantages over running it as a CGI. Setting it up this way is fairly straightforward:

Obtain mod_fcgid from » http://httpd.apache.org/mod_fcgid/. Win32 binaries are available for download from that site. Install the module according to the instructions that will come with it.

Configure your web server as shown below, taking care to adjust any paths to reflect your how you have installed things on your particular system:

Przykład #3 Configure Apache to run PHP as FastCGI

LoadModule fcgid_module modules/mod_fcgid.so  

# Where is your php.ini file?
FcgidInitialEnv PHPRC        "c:/php" 

AddHandler fcgid-script .php  
FcgidWrapper "c:/php/php-cgi.exe" .php  
Files with a .php extension will now be executed by the PHP FastCGI wrapper.



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!!!



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.

See the Wiki documentation at: » http://wiki.php.net/internals/windows/stepbystepbuild



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.exe,0"

[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 a command line 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 on Cloud Computing platforms

Spis treści

PHP installs on the cloud. To the PHP cloud!


Microsoft Azure

PHP installs on the » Azure cloud platform.

See also the » Azure SDK for PHP.



Amazon EC2

PHP installs on the » EC2 cloud platform.

See also the » AWS SDK for PHP.




FastCGI Process Manager (FPM)

Spis treści

FPM (FastCGI Process Manager) is an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites.

These features include:

  • advanced process management with graceful stop/start;

  • ability to start workers with different uid/gid/chroot/environment, listening on different ports and using different php.ini (replaces safe_mode);

  • stdout and stderr logging;

  • emergency restart in case of accidental opcode cache destruction;

  • accelerated upload support;

  • "slowlog" - logging scripts (not just their names, but their PHP backtraces too, using ptrace and similar things to read remote process' execute_data) that are executed unusually slow;

  • fastcgi_finish_request() - special function to finish request and flush all data while continuing to do something time-consuming (video converting, stats processing etc.);

  • dynamic/static child spawning;

  • basic SAPI status info (similar to Apache mod_status);

  • php.ini-based config file.


Installation

Compiling from sources

In order to enable FPM in your PHP build you need to add --enable-fpm to your configure line.

There are several other FPM-specific configure options (all of them optional):

  • --with-fpm-user - set FPM user (default - nobody).

  • --with-fpm-group - set FPM group (default - nobody).



Configuration

FPM uses php.ini syntax for its configuration file - php-fpm.conf.

List of global php-fpm.conf directives

pid string

Path to PID file. Default value: none.

error_log string

Path to error log file. Default value: #INSTALL_PREFIX#/log/php-fpm.log.

log_level string

Error log level. Possible values: alert, error, warning, notice, debug. Default value: notice.

emergency_restart_threshold int

If this number of child processes exit with SIGSEGV or SIGBUS within the time interval set by emergency_restart_interval then FPM will restart. A value of 0 means 'Off'. Default value: 0 (Off).

emergency_restart_interval mixed

Interval of time used by emergency_restart_interval to determine when a graceful restart will be initiated. This can be useful to work around accidental corruptions in an accelerator's shared memory. Available Units: s(econds), m(inutes), h(ours), or d(ays). Default Unit: seconds. Default value: 0 (Off).

process_control_timeout mixed

Time limit for child processes to wait for a reaction on signals from master. Available units: s(econds), m(inutes), h(ours), or d(ays) Default Unit: seconds. Default value: 0.

daemonize boolean

Send FPM to background. Set to 'no' to keep FPM in foreground for debugging. Default value: yes.

List of pool directives

With FPM you can run several pools of processes with different setting. These are settings that can be tweaked per pool.

listen string

The address on which to accept FastCGI requests. Valid syntaxes are: 'ip.add.re.ss:port', 'port', '/path/to/unix/socket'. This option is mandatory for each pool.

listen.backlog int

Set listen(2) backlog. A value of '-1' means unlimited. Default value: -1.

listen.allowed_clients string

List of ipv4 addresses of FastCGI clients which are allowed to connect. Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original PHP FastCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address must be separated by a comma. If this value is left blank, connections will be accepted from any ip address. Default value: any.

listen.owner string

Set permissions for unix socket, if one is used. In Linux, read/write permissions must be set in order to allow connections from a web server. Many BSD-derived systems allow connections regardless of permissions. Default values: user and group are set as the running user, mode is set to 0666.

listen.group string

See listen.owner.

listen.mode string

See listen.owner.

user string

Unix user of FPM processes. This option is mandatory.

group string

Unix group of FPM processes. If not set, the default user's group is used.

pm string

Choose how the process manager will control the number of child processes. Possible values: static, ondemand, dynamic. This option is mandatory.

static - the number of child processes is fixed (pm.max_children).

ondemand - the processes spawn on demand (when requested, as opposed to dynamic, where pm.start_servers are started when the service is started.

dynamic - the number of child processes is set dynamically based on the following directives: pm.max_children, pm.start_servers, pm.min_spare_servers, pm.max_spare_servers.

pm.max_children int

The number of child processes to be created when pm is set to static and the maximum number of child processes to be created when pm is set to dynamic. This option is mandatory.

This option sets the limit on the number of simultaneous requests that will be served. Equivalent to the ApacheMaxClients directive with mpm_prefork and to the PHP_FCGI_CHILDREN environment variable in the original PHP FastCGI.

pm.start_servers in

The number of child processes created on startup. Used only when pm is set to dynamic. Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2.

pm.min_spare_servers int

The desired minimum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_spare_servers int

The desired maximum number of idle server processes. Used only when pm is set to dynamic. Also mandatory in this case.

pm.max_requests int

The number of requests each child process should execute before respawning. This can be useful to work around memory leaks in 3rd party libraries. For endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS. Default value: 0.

pm.status_path string

The URI to view the FPM status page. If this value is not set, no URI will be recognized as a status page. Default value: none.

ping.path string

The ping URI to call the monitoring page of FPM. If this value is not set, no URI will be recognized as a ping page. This could be used to test from outside that FPM is alive and responding. Please note that the value must start with a leading slash (/).

ping.response string

This directive may be used to customize the response to a ping request. The response is formatted as text/plain with a 200 response code. Default value: pong.

request_terminate_timeout mixed

The timeout for serving a single request after which the worker process will be killed. This option should be used when the 'max_execution_time' ini option does not stop script execution for some reason. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

request_slowlog_timeout mixed

The timeout for serving a single request after which a PHP backtrace will be dumped to the 'slowlog' file. A value of '0' means 'Off'. Available units: s(econds)(default), m(inutes), h(ours), or d(ays). Default value: 0.

slowlog string

The log file for slow requests. Default value: #INSTALL_PREFIX#/log/php-fpm.log.slow.

rlimit_files int

Set open file descriptor rlimit. Default value: system defined value.

rlimit_core int

Set max core size rlimit. Possible Values: 'unlimited' or an integer greater or equal to 0. Default value: system defined value.

chroot string

Chroot to this directory at the start. This value must be defined as an absolute path. When this value is not set, chroot is not used.

chdir string

Chdir to this directory at the start. This value must be an absolute path. Default value: current directory or / when chroot.

catch_workers_output boolean

Redirect worker stdout and stderr into main error log. If not set, stdout and stderr will be redirected to /dev/null according to FastCGI specs. Default value: no.

It's possible to pass additional environment variables and update PHP settings of a ceratian pool. To do this, you need to add the following options to php-fpm.conf

Przykład #1 Passing environment variables and PHP settings to a pool

env[HOSTNAME] = $HOSTNAME
       env[PATH] = /usr/local/bin:/usr/bin:/bin
       env[TMP] = /tmp
       env[TMPDIR] = /tmp
       env[TEMP] = /tmp

       php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
       php_flag[display_errors] = off
       php_admin_value[error_log] = /var/log/fpm-php.www.log
       php_admin_flag[log_errors] = on
       php_admin_value[memory_limit] = 32M
PHP settings passed with php_value or php_flag will overwrite their previous value. Please note that defining disable_functions or disable_classes will not overwrite previously defined php.ini values, but will append the new value instead.

Settings defined with php_admin_value and php_admin_flag cannot be overriden with ini_set().




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 PHP 4) 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 --help to display additional usage information.



php-config

php-config is a simple shell script for obtaining information about the installed PHP configuration.

When compiling extensions, if you have multiple PHP versions installed, you may specify for which installation you'd like to build by using the --with-php-config option during configuration, specifying the path of the respective php-config script.

The list of command line options provided by the php-config script can be queried anytime by running php-config with the -h switch:

Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [...]
  --includes          [...]
  --ldflags           [...]
  --libs              [...]
  --extension-dir     [...]
  --include-dir       [...]
  --php-binary        [...]
  --php-sapis         [...]
  --configure-options [...]
  --version           [...]
  --vernum            [...]

Command line options
Option Description
--prefix Directory prefix where PHP is installed, e.g. /usr/local
--includes List of -I options with all include files
--ldflags LD Flags which PHP was compiled with
--libs Extra libraries which PHP was compiled with
--extension-dir Directory where extensions are searched by default
--include-dir Directory prefix where header files are installed by default
--php-binary Full path to php CLI or CGI binary
--php-sapis Show all SAPI modules available
--configure-options Configure options to recreate configuration of current PHP installation
--version PHP version
--vernum PHP version as integer



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 versions, it happens on every invocation.

php.ini is searched for 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 any of these keys, 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 the SAPI in use, so, for example, php-cli.ini or php-apache.ini), it is used instead of php.ini. The SAPI name can be determined with 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 on the respective pages of the extensions themselves. A list of the core directives is available in the appendix. Not all PHP directives are necessarily documented in this manual: for a complete list of directives available in your PHP version, please read your well commented php.ini file. Alternatively, you may find » 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']). In case the PHP file is outside the document root, only its directory is scanned.

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 Meaning
PHP_INI_USER Entry can be set in user scripts (like with ini_set()) or in the Windows registry
PHP_INI_PERDIR Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM Entry can be set in php.ini or httpd.conf
PHP_INI_ALL Entry can be set anywhere



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

Przykład #1 Apache configuration example

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine 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.

Informacja:

W PHP 5.2 i wcześniejszych, parser nie pozwalał, aby znacznik otwierający <?php był jedynym znakiem w pliku. Dozwolone jest to od PHP 5.3.

Informacja:

Począwszy od PHP 5.4, krótkie znaczniki <?= są zawsze rozpoznawane i ważne, niezależnie od ustawień short_open_tag.



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 three 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 $a_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.

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, the result of an operator which returns a boolean value is passed on to a control structure.

<?php
// == is an operator which tests
// 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 this can be used with exactly the same meaning:
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 unnecessary, 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 ℤ = {..., -2, -1, 0, 1, 2, ...}.

See also:

Syntax

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

Binary integer literals are available since PHP 5.4.0.

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

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]+

binary      : 0b[01]+

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

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-bit platforms usually have a 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.

Przykład #3 Integer overflow on a 32-bit system

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

$large_number 2147483648;
var_dump($large_number);                     // float(2147483648)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);                     // float(50000000000)
?>

Przykład #4 Integer overflow on a 64-bit system

<?php
$large_number 
9223372036854775807;
var_dump($large_number);                     // int(9223372036854775807)

$large_number 9223372036854775808;
var_dump($large_number);                     // float(9.2233720368548E+18)

$million 1000000;
$large_number =  50000000000000 $million;
var_dump($large_number);                     // float(5.0E+19)
?>

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 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms), 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

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they 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.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly 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.

Comparing floats

As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

$a and $b are equal to 5 digits of precision.

<?php
$a 
1.23456789;
$b 1.23456780;
$epsilon 0.00001;

if(
abs($a-$b) < $epsilon) {
    echo 
"true";
}
?>

NaN

Some numeric operations can result in a value represented by the constant NAN. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, will have a result of FALSE.

Because NAN represents any number of different values, NAN should not be compared to other values, including itself, and instead should be checked for using is_nan().



Strings

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. See details of the string type.

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, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

Informacja: Unlike the double-quoted and heredoc 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)
\e escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\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, it's 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;
}
?>

Starting with PHP 5.3.0, the opening Heredoc identifier may optionally be enclosed in double quotes:

Przykład #5 Using double quotes in Heredoc

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

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 <<< sequence 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 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
$juice 
"apple";

echo 
"He drank some $juice juice.".PHP_EOL;
// Invalid. "s" is a valid character for a variable name, but the variable is $juice.
echo "He drank some juice made of $juices.";
?>

Powyższy przykład wyświetli:

He drank some apple juice.
He drank some juice made of .

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.

Przykład #8 Simple syntax example

<?php
$juices 
= array("apple""orange""koolaid1" => "purple");

echo 
"He drank some $juices[0] juice.".PHP_EOL;
echo 
"He drank some $juices[1] juice.".PHP_EOL;
echo 
"He drank some juice made of $juice[0]s.".PHP_EOL// Won't work
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class 
people {
    public 
$john "John Smith";
    public 
$jane "Jane Smith";
    public 
$robert "Robert Paulsen";
    
    public 
$smith "Smith";
}

$people = new people();

echo 
"$people->john drank some $juices[0] juice.".PHP_EOL;
echo 
"$people->john then said hello to $people->jane.".PHP_EOL;
echo 
"$people->john's wife greeted $people->robert.".PHP_EOL;
echo 
"$people->robert greeted the two $people->smiths."// Won't work
?>

Powyższy przykład wyświetli:

He drank some apple juice.
He drank some orange juice.
He drank some juice made of s.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

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.

Any scalar variable, array element or object property with a string representation can be included via 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, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// 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()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {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. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Informacja: Strings may also be accessed using braces, as in $str{42}, for the same purpose.

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 NULL byte.

Przykład #9 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 (not including arrays or objects implementing the appropriate interfaces) 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.

Details of the String Type

The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer. There are no limitations on the values the string can be composed of; in particular, bytes with value 0 (“NUL bytes”) are allowed anywhere in the string (however, a few functions, said in this manual not to be “binary safe”, may hand off the strings to libraries that ignore data after a NUL byte.)

This nature of the string type explains why there is no separate “byte” type in PHP – strings take this role. Functions that return no textual data – for instance, arbitrary data read from a network socket – will still return strings.

Given that PHP does not dictate a specific encoding for strings, one might wonder how string literals are encoded. For instance, is the string "á" equivalent to "\xE1" (ISO-8859-1), "\xC3\xA1" (UTF-8, C form), "\x61\xCC\x81" (UTF-8, D form) or any other possible representation? The answer is that string will be encoded in whatever fashion it is encoded in the script file. Thus, if the script is written in ISO-8859-1, the string will be encoded in ISO-8859-1 and so on. However, this does not apply if Zend Multibyte is enabled; in that case, the script may be written in an arbitrary encoding (which is explicity declared or is detected) and then converted to a certain internal encoding, which is then the encoding that will be used for the string literals. Note that there are some constraints on the encoding of the script (or on the internal encoding, should Zend Multibyte be enabled) – this almost always means that this encoding should be a compatible superset of ASCII, such as UTF-8 or ISO-8859-1. Note, however, that state-dependent encodings where the same byte values can be used in initial and non-initial shift states may be problematic.

Of course, in order to useful, functions that operate on text may have to make some assumptions about how the string is encoded. Unfortunately, there is much variation on this matter throughout PHP’s functions:

  • Some functions assume that the string is encoded in some (any) single-byte encoding, but they do not need to interpret those bytes as specific characters. This is case of, for instance, substr(), strpos(), strlen() or strcmp(). Another way to think of these functions is that operate on memory buffers, i.e., they work with bytes and byte offsets.
  • Other functions are passed the encoding of the string, possibly they also assume a default if no such information is given. This is the case of htmlentities() and the majority of the functions in the mbstring extension.
  • Others use the current locale (see setlocale()), but operate byte-by-byte. This is the case of strcasecmp(), strtoupper() and ucfirst(). This means they can be used only with single-byte encodings, as long as the encoding is matched by the locale. For instance strtoupper("á") may return "Á" if the locale is correctly set and á is encoded with a single byte. If it is encoded in UTF-8, the correct result will not be returned and the resulting string may or may not be returned corrupted, depending on the current locale.
  • Finally, they may just assume the string is using a specific encoding, usually UTF-8. This is the case of most functions in the intl extension and in the PCRE extension (in the last case, only when the u modifier is used). Although this is due to their special purpose, the function utf8_decode() assumes a UTF-8 encoding and the function utf8_encode() assumes an ISO-8859-1 encoding.

Ultimately, this means writing correct programs using Unicode depends on carefully avoiding functions that will not work and that most likely will corrupt the data and using instead the functions that do behave correctly, generally from the intl and mbstring extensions. However, using functions that can handle Unicode encodings is just the beginning. No matter the functions the language provides, it is essential to know the Unicode specification. For instance, a program that assumes there is only uppercase and lowercase is making a wrong assumption.



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 using the array() language construct. It takes any number of comma-separated key => value pairs as arguments.

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

It is possible to write a comma after last element or omit it. Result is the same, array(1, 2) === array(1, 2,). Writing comma after last element is useful mainly when formatting array definition on multiple lines (see next example).

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Przykład #1 A simple array

<?php
$array 
= array(
    
"foo" => "bar",
    
"bar" => "foo",
);

// as of PHP 5.4
$array = [
    
"foo" => "bar",
    
"bar" => "foo",
];
?>

The key can either be an integer or a string. The value can be of any type.

Additionally the following key casts will occur:

  • Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
  • Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
  • Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
  • Null will be cast to the empty string, i.e. the key null will actually be stored under "".
  • Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Przykład #2 Type Casting and Overwriting example

<?php
$array 
= array(
    
1    => "a",
    
"1"  => "b",
    
1.5  => "c",
    
true => "d",
);
var_dump($array);
?>

Powyższy przykład wyświetli:

array(1) {
  [1]=>
  string(1) "d"
}

As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assined value "d" is the only one left over.

PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays.

Przykład #3 Mixed integer and string keys

<?php
$array 
= array(
    
"foo" => "bar",
    
"bar" => "foo",
    
100   => -100,
    -
100  => 100,
);
var_dump($array);
?>

Powyższy przykład wyświetli:

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

The key is optional. If it is not specified, PHP will use the increment of the largest previously used integer key.

Przykład #4 Indexed arrays without key

<?php
$array 
= array("foo""bar""hallo""world");
var_dump($array);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hallo"
  [3]=>
  string(5) "world"
}

It is possible to specify the key only for some elements and leave it out for others:

Przykład #5 Keys not on all elements

<?php
$array 
= array(
         
"a",
         
"b",
    
=> "c",
         
"d",
);
var_dump($array);
?>

Powyższy przykład wyświetli:

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6.

Accessing array elements with square bracket syntax

Array elements can be accessed using the array[key] syntax.

Przykład #6 Accessing array elements

<?php
$array 
= array(
    
"foo" => "bar",
    
42    => 24,
    
"multi" => array(
         
"dimensional" => array(
             
"array" => "foo"
         
)
    )
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

Powyższy przykład wyświetli:

string(3) "bar"
int(24)
string(3) "foo"

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

Przykład #7 Array dereferencing

<?php
function getArray() {
    return array(
123);
}

// on PHP 5.4
$secondElement getArray()[1];

// previously
$tmp getArray();
$secondElement $tmp[1];

// or
list(, $secondElement) = getArray();
?>

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.

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. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.

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 (but at least 0). 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 #8 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 #9 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 #10 Changing element in the loop

<?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 #11 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 #12 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 #13 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 #14 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.

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.

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 constant NULL.

<?php
$var 
NULL;       
?>

See also the functions is_null() and unset().

Casting to NULL

Casting a variable to null using (unset) $var will not remove the variable or unset its value. It will only return a NULL value.



Callbacks

Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for the same purpose.

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.

Passing

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. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.

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

Informacja:

Wywołania zwrotne zdefiniowane za pomocą takich funkcji jak call_user_func() i call_user_func_array() nie zostaną aktywowane jeśli w poprzednim wywołaniu zostanie wygenerowany nieobsłużony wyjątek.



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

callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means exactly the same.

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
  • (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 takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression).

Operators can be grouped according to the number of values they take. Unary operators take only one value, for example ! (the logical not operator) or ++ (the increment operator). Binary operators take two values, such as the familiar arithmetical operators + (plus) and - (minus), and the majority of PHP operators fall into this category. Finally, there is a single ternary operator, ? :, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator).

A full list of PHP operators follows in the section Operator Precedence. This also explains operator Presedence and Associativity, which govern exactly how expressions containing several different operators are evaluated.


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.

When operators have equal precedence, their associativity decides whether they are evaluated starting from the right, or starting from the left - see the examples below.

The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides the order of evaluation.

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

For operators of equal precedence, left associativity means that evaluation proceeds from left to right, and 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

// mixing ++ and + produces undefined behavior
$a 1;
echo ++
$a $a++; // may print 4 or 5
?>
Use of parentheses, even when not strictly necessary, can often 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.

The result of the modulus operator % has the same sign as the dividend — that is, the result of $a % $b will have the same sign as $a. For example:

<?php

echo (3)."\n";           // prints 2
echo (% -3)."\n";          // prints 2
echo (-3)."\n";          // prints -2
echo (-% -3)."\n";         // prints -2

?>

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

?>

For arrays, assigning a value to a named key is performed using the "=>" operator. The precedence of this operator is the same as other assignment operators.

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.

An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.

Assignment by Reference

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.

Przykład #1 Assigning by reference

<?php
$a 
3;
$b = &$a// $b is a reference to $a

print "$a\n"// prints 3
print "$b\n"// prints 3

$a 4// change $a

print "$a\n"// prints 4
print "$b\n"// prints 4 as well, since $b is a reference to $a, which has
              // been changed
?>

As of PHP 5, the new operator returns a reference automatically, so assigning the result of new by reference results in an E_DEPRECATED message in PHP 5.3 and later, and an E_STRICT message in earlier versions.

For example, this code will result in a warning:

<?php
class {}

/* The following line generates the following error message:
 * Deprecated: Assigning the return value of new by reference is deprecated in...
 */
$o = &new C;
?>

More information on references and their potential uses can be found in the References Explained section of the manual.



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 after type juggling.
$a === $b Identical TRUE if $a is equal to $b, and they are of the same type.
$a != $b Not equal TRUE if $a is not equal to $b after type juggling.
$a <> $b Not equal TRUE if $a is not equal to $b after type juggling.
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the same type.
$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 a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

<?php
var_dump
(== "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true
var_dump("10" == "1e1"); // 10 == 10 -> true
var_dump(100 == "1e2"); // 100 == 100 -> 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.

Ostrzeżenie

Comparison of floating point numbers

Because of the way floats are represented internally, you should not test two floats for equality.

See the documentation for float for more information.

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 you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

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.

Informacja:

Unlike some other languages, backticks cannot be used within double-quoted strings.

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 PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 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. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

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: (($f = 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 returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

<?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

(PHP 4, PHP 5)

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

(PHP 4, PHP 5)

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

(PHP 4, PHP 5)

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 4, PHP 5)

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;
?>

Informacja:

Mixing syntaxes in the same control block is not supported.

See also while, for, and if for further examples.



while

(PHP 4, PHP 5)

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

(PHP 4, PHP 5)

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

(PHP 4, PHP 5)

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, PHP 5)

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, 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:

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 iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

The second form will additionally assign the current element's key to the $key variable on each iteration.

It is possible to customize object iteration.

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.

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?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
?>

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). 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

(PHP 4, PHP 5)

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;
    }
}
?>

Changelog for break
Wersja Opis
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.



continue

(PHP 4, PHP 5)

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.

Informacja:

continue 0; and continue 1; is the same as running continue;.

<?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;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 entire continue print "$i\n"; is evaluated as a single expression, and so print() is called only when $i == 2 is true. (The return value of print is passed to continue as the numeric argument.)

Changelog for continue
Wersja Opis
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; continue $num;) as the numerical argument.



switch

(PHP 4, PHP 5)

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;
?>

It's 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

(PHP 4, PHP 5)

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.

Note that PHP does not expose whether --enable-zend-multibyte was used to compile PHP other than by phpinfo().



return

(PHP 4, PHP 5)

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

(PHP 4, PHP 5)

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_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()

(PHP 4, PHP 5)

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. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. 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 — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — 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 Supported Protocols and 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 for 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;
        return 
ob_get_clean();
    }
    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()

(PHP 4, PHP 5)

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

(PHP 4, PHP 5)

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

(PHP 5 >= 5.3.0)

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.

What's the worse thing that could happen if you use goto?
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

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

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, the new keyword must be used. An object will always be created 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).

If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

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

$instance 
= new SimpleClass();

$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"
}

PHP 5.3.0 introduced a couple of new ways to create instances of an object:

Przykład #5 Creating new objects

<?php
class Test
{
    static public function 
getNew()
    {
        return new static;
    }
}

class 
Child extends Test
{}

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);

$obj3 Test::getNew();
var_dump($obj3 instanceof Test);

$obj4 Child::getNew();
var_dump($obj4 instanceof Child);
?>

Powyższy przykład wyświetli:

bool(true)
bool(true)
bool(true)

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

When overriding methods, the parameter signature should remain the same or PHP will generate an E_STRICT level error. This does not apply to the constructor, which allows overriding with different parameters.

Przykład #6 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.

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

Wskazówka

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

Informacja:

Prior to 5.3.0, exceptions thrown in the __autoload function could not be caught in the catch block and would result in a fatal error. From 5.3.0+ exceptions thrown in the __autoload function can be caught in the catch block, with 1 provision. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.

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) {
    include 
$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 ...
*/
?>

Przykład #3 Autoloading with exception handling for 5.3.0+

This example throws an exception and demonstrates the try/catch block.

<?php
function __autoload($name) {
    echo 
"Want to load $name.\n";
    throw new 
Exception("Unable to load $name.");
}

try {
    
$obj = new NonLoadableClass();
} catch (
Exception $e) {
    echo 
$e->getMessage(), "\n";
}
?>

Powyższy przykład wyświetli:

Want to load NonLoadableClass.
Unable to load NonLoadableClass.

Przykład #4 Autoloading with exception handling for 5.3.0+ - Missing custom exception

This example throws an exception for a non-loadable, custom exception.

<?php
function __autoload($name) {
    echo 
"Want to load $name.\n";
    throw new 
MissingException("Unable to load $name.");
}

try {
    
$obj = new NonLoadableClass();
} catch (
Exception $e) {
    echo 
$e->getMessage(), "\n";
}
?>

Powyższy przykład wyświetli:

Want to load NonLoadableClass.
Want to load MissingException.

Fatal error: Class 'MissingException' not found in testMissingException.php on line 4



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.

Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

Przykład #2 Constructors in namespaced classes

<?php
namespace Foo;
class 
Bar {
    public function 
Bar() {
        
// treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    
}
}
?>

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 there are no other references to a particular object, or in any order during the shutdown sequence.

Przykład #3 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.

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.

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, 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
?>

Visibility from other objects

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

Przykład #3 Accessing private members of the same object type

<?php
class Test
{
    private 
$foo;

    public function 
__construct($foo)
    {
        
$this->foo $foo;
    }

    private function 
bar()
    {
        echo 
'Accessed the private method.';
    }

    public function 
baz(Test $other)
    {
        
// We can change the private property:
        
$other->foo 'hello';
        
var_dump($other->foo);

        
// We can also call the private method:
        
$other->bar();
    }
}

$test = new Test('test');

$test->baz(new Test('other'));
?>

Powyższy przykład wyświetli:

string(5) "hello"
Accessed the private method.


Object Inheritance

Inheritance is a well-established 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.

Informacja:

Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

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;
?>

Three special keywords self, parent and static 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();
?>

See also some examples of static call trickery.



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. Classes defined as abstract may not be instantiated, and 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. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ.

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

It's possible for interfaces to have constants. Interface constants works exactly like class constants except they cannot be overridden by a class/interface that inherits them.

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 it's not allowed to 
// override 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.



Traits

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

Traits is a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Przykład #1 Trait example

<?php
trait ezcReflectionReturnInfo 
{
    function 
getReturnType() { /*1*/ }
    function 
getReturnDescription() { /*2*/ }
}

class 
ezcReflectionMethod extends ReflectionMethod {
    use 
ezcReflectionReturnInfo;
    
/* ... */
}

class 
ezcReflectionFunction extends ReflectionFunction {
    use 
ezcReflectionReturnInfo;
    
/* ... */
}
?>

Precedence

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in return override inherited methods.

Przykład #2 Precedence Order Example

An inherited method from a base class is overridden by the method inserted into MyHelloWorld from the SayWorld Trait. The behavior is the same for methods defined in the MyHelloWorld class. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.

<?php
class Base {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait SayWorld {
    public function 
sayHello() {
        
parent::sayHello();
        echo 
'World!';
    }
}

class 
MyHelloWorld extends Base {
    use 
SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

Powyższy przykład wyświetli:

Hello World!

Przykład #3 Alternate Precedence Order Example

<?php
trait HelloWorld 
{
    public function 
sayHello() {
        echo 
'Hello World!';
    }
}

class 
TheWorldIsNotEnough {
    use 
HelloWorld;
    public function 
sayHello() {
        echo 
'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
?>

Powyższy przykład wyświetli:

Hello Universe!

Multiple Traits

Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.

Przykład #4 Multiple Traits Usage

<?php
trait Hello 
{
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait World {
    public function 
sayWorld() {
        echo 
'World';
    }
}

class 
MyHelloWorld {
    use 
HelloWorld;
    public function 
sayExclamationMark() {
        echo 
'!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

Powyższy przykład wyświetli:

Hello World!

Conflict Resolution

If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to chose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the as operator can be used to allow the inclusion of one of the conflicting methods under another name.

Przykład #5 Conflict Resolution

In this example, Talker uses the traits A and B. Since A and B have conflicting methods, it defines to use the variant of smallTalk from trait B, and the variant of bigTalk from trait A.

The Aliased_Talker makes use of the as operator to be able to use B's bigTalk implementation under an additional alias talk.

<?php
trait A 
{
    public function 
smallTalk() {
        echo 
'a';
    }
    public function 
bigTalk() {
        echo 
'A';
    }
}

trait B {
    public function 
smallTalk() {
        echo 
'b';
    }
    public function 
bigTalk() {
        echo 
'B';
    }
}

class 
Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
    }
}

class 
Aliased_Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
        
B::bigTalk as talk;
    }
}
?>

Changing Method Visibility

Using the as syntax, one can also adjust the visibility of the method in the exhibiting class.

Przykład #6 Changing Method Visibility

<?php
trait HelloWorld 
{
    public function 
sayHello() {
        echo 
'Hello World!';
    }
}

// Change visibility of sayHello
class MyClass1 {
    use 
HelloWorld sayHello as protected; }
}

// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
    use 
HelloWorld sayHello as private myPrivateHello; }
}
?>

Traits Composed from Traits

Just as classes can make use of traits, so can other traits. By using one or more traits in a trait definition, it can be composed partially or entirely of the members defined in those other traits.

Przykład #7 Traits Composed from Traits

<?php
trait Hello 
{
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait World {
    public function 
sayWorld() {
        echo 
'World!';
    }
}

trait HelloWorld {
    use 
HelloWorld;
}

class 
MyHelloWorld {
    use 
HelloWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>

Powyższy przykład wyświetli:

Hello World!

Abstract Trait Members

Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.

Przykład #8 Express Requirements by Abstract Methods

<?php
trait Hello 
{
    public function 
sayHelloWorld() {
        echo 
'Hello'.$this->getWorld();
    }
    abstract public function 
getWorld();
}

class 
MyHelloWorld {
    private 
$world;
    use 
Hello;
    public function 
getWorld() {
        return 
$this->world;
    }
    public function 
setWorld($val) {
        
$this->world $val;
    }
}
?>

Static Trait Members

Static variables can be referred to in trait methods, but cannot be defined by the trait. Traits can, however, define static methods for the exhibiting class.

Przykład #9 Static Variables

<?php
trait Counter 
{
    public function 
inc() {
        static 
$c 0;
        
$c $c 1;
        echo 
"$c\n";
    }
}

class 
C1 {
    use 
Counter;
}

class 
C2 {
    use 
Counter;
}

$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

Przykład #10 Static Methods

<?php
trait StaticExample 
{
    public static function 
doSomething() {
        return 
'Doing something';
    }
}

class 
Example {
    use 
StaticExample;
}

Example::doSomething();
?>

Properties

Traits can also define properties.

Przykład #11 Defining Properties

<?php
trait PropertiesTrait 
{
    public 
$x 1;
}

class 
PropertiesExample {
    use 
PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

If a trait defines a property then a class can not define a property with the same name, otherwise an error is issued. It is an E_STRICT if the class definition is compatible (same visibility and initial value) or fatal error otherwise.

Przykład #12 Conflict Resolution

<?php
trait PropertiesTrait 
{
    public 
$same true;
    public 
$different false;
}

class 
PropertiesExample {
    use 
PropertiesTrait;
    public 
$same true// Strict Standards
    
public $different true// Fatal error
}
?>


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

public void __set ( string $name , mixed $value )
public mixed __get ( string $name )
public bool __isset ( string $name )
public 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 should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is 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 assignments together like this:

 $a = $obj->b = 8; 

Informacja:

It is not possible to use overloaded properties in other language constructs than isset(). This means if empty() is called on an overloaded property, the overloaded method is not called.

To workaround that limitation, the overloaded property must be copied into a local variable in the scope and then be handed to empty().

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

public mixed __call ( string $name , array $arguments )
public static 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()
    {
        
$key key($this->var);
        
$var = ($key !== NULL && $key !== 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
valid: 1
current: 1
key: 0
0: 1
next: 2
valid: 1
current: 2
key: 1
1: 2
next: 3
valid: 1
current: 3
key: 2
2: 3
next:
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 an SQLite Driver
$sqlite Example::factory('SQLite');
?>

Singleton

The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Singleton is a "Gang of Four" Creational Pattern.

The Singleton pattern is often implemented in Database Classes, Loggers, Front Controllers or Request and Response objects.

Przykład #2 Singleton example

<?php
class Example
{
    private static 
$instance;
    private 
$count 0;

    private function 
__construct()
    {
    }

    public static function 
singleton()
    {
        if (!isset(
self::$instance)) {
            echo 
'Creating new instance.';
            
$className __CLASS__;
            
self::$instance = new $className;
        }
        return 
self::$instance;
    }

    public function 
increment()
    {
        return 
$this->count++;
    }

    public function 
__clone()
    {
        
trigger_error('Clone is not allowed.'E_USER_ERROR);
    }

    public function 
__wakeup()
    {
        
trigger_error('Unserializing is not allowed.'E_USER_ERROR);
    }
}
?>

Illustrated below is how the Singleton behaves

<?php
$singleton 
Example::singleton(); // prints "Creating new instance."
echo $singleton->increment(); // 0
echo $singleton->increment(); // 1

$singleton Example::singleton(); // reuses existing instance now
echo $singleton->increment(); // 2
echo $singleton->increment(); // 3

// all of these will raise a Fatal Error
$singleton2 = new Example;
$singleton3 = clone $singleton;
$singleton4 unserialize(serialize($singleton));
?>
Ostrzeżenie

The Singleton pattern is one of the more controversial patterns. Critics argue that Singletons introduce Global State into an application and tightly couple the Singleton and its consuming classes. This leads to hidden dependencies and unexpected side-effects, which in turn leads to code that is harder to test and maintain.

Critics further argue that it is pointless to use a Singleton in a Shared Nothing Architecture like PHP where objects are unique within the Request only anyways. It is easier and cleaner to create collaborator object graphs by using Builders and Factory patterns once at the beginning of the Request.

Singletons also violate several of the "SOLID" OOP design principles and the Law of Demeter. Singletons cannot be serialized. They cannot be subtyped (before PHP 5.3) and won't be Garbage Collected because of the instance being stored as a static attribute of the Singleton.



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

public array __sleep ( void )
void __wakeup ( void )

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.

Informacja:

It is not possible for __sleep() to return names of private properties in parent classes. Doing this will result in an E_NOTICE level error. Instead you may use the Serializable interface.

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

public string __toString ( void )

The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

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

mixed __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
{
    public 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()

static object __set_state ( array $properties )

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.

void __clone ( void )

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), interfaces, arrays (since PHP 5.1) or callable (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call.

If class or interface is specified as type hint then all its children or implementations are allowed too.

Type hints can not be used with scalar types such as int or string. Traits are not allowed either.

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);
    }
    
    
/**
     * First parameter must be iterator
     */
    
public function test_interface(Traversable $iterator) {
        echo 
get_class($iterator);
    }
    
    
/**
     * First parameter must be callable
     */
    
public function test_callable(callable $callback$data) {
        
call_user_func($callback$data);
    }
}

// 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'));

// Works: Prints ArrayObject
$myclass->test_interface(new ArrayObject(array()));

// Works: Prints int(1)
$myclass->test_callable('var_dump'1);
?>

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

?>


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.

More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.

This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not 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:

In non-static contexts, the called class will be the class of the object instance. Since $this-> will try to call private methods from the same scope, using static:: may give different results. Another difference is that static:: can only refer to static properties.

Przykład #3 static:: usage in a non-static context

<?php
class {
    private function 
foo() {
        echo 
"success!\n";
    }
    public function 
test() {
        
$this->foo();
        static::
foo();
    }
}

class 
extends {
   
/* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class 
extends {
    private function 
foo() {
        
/* original method is replaced; the scope of the new one is C */
    
}
}

$b = new B();
$b->test();
$c = new C();
$c->test();   //fails
?>

Powyższy przykład wyświetli:

success!
success!
success!


Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

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



Objects and references

One of the key-points of PHP 5 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 PHP 5, 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 variables contained in 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 present 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, the session_register() is removed since PHP 5.4.0.

It is strongly recommended that if an application serializes objects, for use later in the application, that the application includes 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.



OOP Changelog

Changes to the PHP 5 OOP model are logged here. Descriptions and other notes regarding these features are documented within the OOP 5 documentation.

Wersja Opis
5.4.0 Changed: If an abstract class defines a signature for the constructor it will now be enforced.
5.3.3 Changed: Methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.
5.3.0 Changed: Classes that implement interfaces with methods that have default values in the prototype are no longer required to match the interface's default value.
5.3.0 Changed: It's now possible to reference the class using a variable (e.g., echo $classname::constant;). The variable's value can not be a keyword (e.g., self, parent or static).
5.3.0 Changed: An E_WARNING level error is issued if the magic overloading methods are declared static. It also enforces the public visibility requirement.
5.3.0 Changed: Prior to 5.3.0, exceptions thrown in the __autoload() function could not be caught in the catch block, and would result in a fatal error. Exceptions now thrown in the __autoload function can be caught in the catch block, with one proviso. If throwing a custom exception, then the custom exception class must be available. The __autoload function may be used recursively to autoload the custom exception class.
5.3.0 Added: The __callStatic method.
5.3.0 Added: heredoc and nowdoc support for class const and property definitions. Note: heredoc values must follow the same rules as double-quoted strings, (e.g., no variables within).
5.3.0 Added: Late Static Bindings.
5.3.0 Added: The __invoke() method.
5.2.0 Changed: The __toString() method was only called when it was directly combined with echo() or print(). But now, 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 a __toString method to string emits a E_RECOVERABLE_ERROR level error.
5.1.3 Changed: In previous versions of PHP 5, the use of var was considered deprecated and would issue an E_STRICT level error. It's no longer deprecated, therefore does not emit the error.
5.1.0 Changed: The __set_state() static method is now called for classes exported by var_export().
5.1.0 Added: The __isset() and __unset() methods.




Namespaces

Spis treści


Namespaces overview

(PHP 5 >= 5.3.0)

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, interfaces, 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
?>

Informacja:

Namespace names PHP and php, and compound names starting with these names (like PHP\Classes) are reserved for internal language use and should not be used in the userspace code.



Defining namespaces

(PHP 5 >= 5.3.0)

Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, interfaces, 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

(PHP 5 >= 5.3.0)

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

(PHP 5 >= 5.3.0)

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

(PHP 5 >= 5.3.0)

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 5 >= 5.3.0)

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 5 >= 5.3.0)

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

(PHP 5 >= 5.3.0)

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 three kinds of aliasing or importing: aliasing a class name, aliasing an interface 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 recommended, 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
?>

Scoping rules for importing

The use keyword must be declared in the outermost scope of a file (the global scope) or inside namespace declarations. This is because the importing is done at compile time and not runtime, so it cannot be block scoped. The following example will show an illegal use of the use keyword:

Przykład #5 Illegal importing rule

<?php
namespace Languages;

class 
Greenlandic
{
    use 
Languages\Danish;

    ...
}
?>

Informacja:

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.



Global space

(PHP 5 >= 5.3.0)

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

(PHP 5 >= 5.3.0)

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 "2"
if (is_array('hi')) { // prints "is not array"
    
echo "is array\n";
} else {
    echo 
"is not array\n";
}
?>



Name resolution rules

(PHP 5 >= 5.3.0)

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"
              // if class "A\B" not found, it tries to autoload class "A\B"
?>


FAQ: things you need to know about namespaces

(PHP 5 >= 5.3.0)

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

The thrown object must be an instance of the Exception class or a subclass of Exception. Trying to throw an object that is not will result in a PHP Fatal Error.

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 fatal E_ERROR error.

Przykład #2 Extending the Exception class (PHP 5.3.0+)

<?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";
?>

Informacja:

Versions of PHP 5, prior to PHP 5.3.0 do not support nesting of exceptions. The following code fragment can be used as a replacement MyException class if you wish to run this example.

<?php
/**
 * Define a custom exception class
 */
class MyException extends Exception
{
    
// Redefine the exception so message isn't optional
    
public function __construct($message$code 0) {
        
// some code
    
        // make sure everything is assigned properly
        
parent::__construct($message$code);
    }

    
// 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";
    }
}
?>




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

(PHP 4, PHP 5)

$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]

(PHP 4 >= 4.1.0, PHP 5)

$_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.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.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.
'REMOTE_USER'
The authenticated user.
'REDIRECT_REMOTE_USER'
The authenticated user if the request is internally redirected.
'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 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 doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When 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.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.

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]

(PHP 4 >= 4.1.0, PHP 5)

$_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.

Informacja:

The GET variables are passed through urldecode().



$_POST

$HTTP_POST_VARS [deprecated]

(PHP 4 >= 4.1.0, PHP 5)

$_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]

(PHP 4 >= 4.1.0, PHP 5)

$_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

(PHP 4 >= 4.1.0, PHP 5)

$_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]

(PHP 4 >= 4.1.0, PHP 5)

$_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]

(PHP 4 >= 4.1.0, PHP 5)

$_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]

(PHP 4 >= 4.1.0, PHP 5)

$_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 4, PHP 5)

$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

(PHP 4, PHP 5)

$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

(PHP 4 >= 4.0.4, PHP 5)

$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. $http_response_header will be created in the local scope.

Przykłady

Przykład #1 $http_response_header example

<?php
function get_contents() {
  
file_get_contents("http://example.com");
  
var_dump($http_response_header);
}
get_contents();
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"
}
NULL



$argc

(PHP 4, PHP 5)

$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 not available when register_argc_argv is disabled.

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

(PHP 4, PHP 5)

$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 $argv[0] is always the name that was used to run the script.

Informacja: This variable is not available when register_argc_argv is disabled.

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"
}

Zobacz też:

  • getopt() - Gets options from the command line argument list


Spis treści



Predefined Exceptions

Spis treści

See also the SPL Exceptions


Exception

(PHP 5 >= 5.1.0)

Wstęp

Exception is the base class for all Exceptions.

Krótki opis klasy

Exception {
/* Właściwości */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* Metody */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )
final public mixed 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

code

The exception code

file

The filename where the exception was created

line

The line where the exception was created


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.

Notatki

Informacja:

The message is NOT binary safe.



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 mixed Exception::getCode ( void )

Returns the Exception code.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the exception code as integer in Exception but possibly as other type in Exception descendants (for example as string in PDOException).

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

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the filename in which the exception was created.

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 )

Get line number where the exception was created.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the line number where the exception was created.

Przykłady

Przykład #1 Exception::getLine() example

<?php
try {
    throw new 
Exception("Some error message");
} catch(
Exception $e) {
    echo 
"The exception was created on line: " $e->getLine();
}
?>

Powyższy przykład wyświetli coś podobnego do:

The exception was created 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

(PHP 5 >= 5.1.0)

Wstęp

An Error Exception.

Krótki opis klasy

ErrorException extends Exception {
/* Właściwości */
protected int $severity ;
/* Metody */
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )
final public int getSeverity ( void )
/* Metody dziedziczone */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed 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::__constructConstructs the exception

Opis

public ErrorException::__construct() ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )

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.

previous

The previous exception used for the exception chaining.



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

(No version information available, might only be in SVN)

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 {
}

This interface has no methods, its only purpose is to be the base interface for all traversable classes.



The Iterator interface

(PHP 5 >= 5.0.0)

Wstęp

Interface for external iterators or objects that can be iterated themselves internally.

Zestawienie interfejsu

Iterator extends Traversable {
/* Metody */
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 )
}

Predefined iterators

PHP already provides a number of iterators for many day to day tasks. See SPL iterators for a list.

Przykłady

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.0.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.0.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, or NULL on failure.

Błędy/Wyjątki

Issues E_NOTICE on failure.



Iterator::next

(PHP 5 >= 5.0.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.0.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.0.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

(PHP 5 >= 5.0.0)

Wstęp

Interface to create an external Iterator.

Zestawienie interfejsu

IteratorAggregate extends Traversable {
/* Metody */
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.0.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

(PHP 5 >= 5.0.0)

Wstęp

Interface to provide accessing objects as arrays.

Zestawienie interfejsu

ArrayAccess {
/* Metody */
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) {
        if (
is_null($offset)) {
            
$this->container[] = $value;
        } else {
            
$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"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

ArrayAccess::offsetExists

(PHP 5 >= 5.0.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.0.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.

Notatki

Informacja:

Starting with PHP 5.3.4, the prototype checks were relaxed and it's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of ArrayAccess objects possible.

A direct modification is one that replaces completely the value of the array dimension, as in $obj[6] = 7. An indirect modification, on the other hand, only changes part of the dimension, or attempts to assign the dimension by reference to another variable, as in $obj[6][7] = 7 or $var =& $obj[6]. Increments with ++ and decrements with -- are also implemented in a way that requires indirect modification.

While direct modification triggers a call to ArrayAccess::offsetSet(), indirect modification triggers a call to ArrayAccess::offsetGet(). In that case, the implementation of ArrayAccess::offsetGet() must be able to return by reference, otherwise an E_NOTICE message is raised.

Zwracane wartości

Can return all value types.

Zobacz też:



ArrayAccess::offsetSet

(PHP 5 >= 5.0.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ść.

Notatki

Informacja:

The offset parameter will be set to NULL if another value is not available, like in the following example.

<?php
$arrayaccess
[] = "first value";
$arrayaccess[] = "second value";
print_r($arrayaccess);
?>

Powyższy przykład wyświetli:

Array
(
    [0] => first value
    [1] => second value
)

Informacja:

This function is not called in assignments by reference and otherwise indirect changes to array dimensions overloaded with ArrayAccess (indirect in the sense they are made not by changing the dimension directly, but by changing a sub-dimension or sub-property or assigning the array dimension by reference to another variable). Instead, ArrayAccess::offsetGet() is called. The operation will only be successful if that method returns by reference, which is only possible since PHP 5.3.4.



ArrayAccess::offsetUnset

(PHP 5 >= 5.0.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

(PHP 5 >= 5.1.0)

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 {
/* Metody */
abstract public string serialize ( void )
abstract public void 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);

var_dump($ser);

$newobj unserialize($ser);

var_dump($newobj->getData());
?>

Powyższy przykład wyświetli coś podobnego do:

string(38) "C:3:"obj":23:{s:15:"My private data";}"
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 void 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

The return value from this method is ignored.

Zobacz też:


Spis treści



The Closure class

(No version information available, might only be in SVN)

Wstęp

Class used to represent anonymous functions.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon. Starting with PHP 5.4, this class has methods that allow further control of the anonymous function after it has been created.

Besides the methods listed here, this class also has an __invoke method. This is for consistency with other classes that implement calling magic, as this method is not used for calling the function.

Krótki opis klasy

Closure {
/* Metody */
__construct ( void )
public static Closure bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )
public Closure bindTo ( object $newthis [, mixed $newscope = 'static' ] )
}

Closure::__construct

(No version information available, might only be in SVN)

Closure::__constructConstructor that disallows instantiation

Opis

Closure::__construct ( void )

This method exists only to disallow instantiation of the Closure class. Objects of this class are created in the fashion described on the anonymous functions page.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

This method has no return value; it simply emits an error (of type E_RECOVERABLE_ERROR).

Zobacz też:



Closure::bind

(No version information available, might only be in SVN)

Closure::bind Duplicates a closure with a specific bound object and class scope

Opis

public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )

This method is a static version of Closure::bindTo(). See the documentation of that method for more information.

Parametry

closure

The anonymous functions to bind.

newthis

The object to which the given anonymous function should be bound, or NULL for the closure to be unbound.

newscope

The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.

Zwracane wartości

Returns a new Closure object lub FALSE w przypadku niepowodzenia

Przykłady

Przykład #1 Closure::bind() example

<?php
class {
    private static 
$sfoo 1;
    private 
$ifoo 2;
}
$cl1 = static function() {
    return 
A::$sfoo;
};
$cl2 = function() {
    return 
$this->ifoo;
};

$bcl1 Closure::bind($cl1null'A');
$bcl2 Closure::bind($cl2, new A(), 'A');
echo 
$bcl1(), "\n";
echo 
$bcl2(), "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

1
2

Zobacz też:



Closure::bindTo

(No version information available, might only be in SVN)

Closure::bindTo Duplicates the closure with a new bound object and class scope

Opis

public Closure Closure::bindTo ( object $newthis [, mixed $newscope = 'static' ] )

Create and return a new anonymous function with the same body and bound variables as this one, but possibly with a different bound object and a new class scope.

The “bound object” determines the value $this will have in the function body and the “class scope” represents a class which determines which private and protected members the anonymous function will be able to access. Namely, the members that will be visible are the same as if the anonymous function were a method of the class given as value of the newscope parameter.

Static closures cannot have any bound object (the value of the parameter newthis should be NULL), but this function can nevertheless be used to change their class scope.

This function will ensure that for a non-static closure, having a bound instance will imply being scoped and vice-versa. To this end, non-static closures that are given a scope but a NULL instance are made static and non-static non-scoped closures that are given a non-null instance are scoped to an unspecified class.

Informacja:

If you only want to duplicate the anonymous functions, you can use cloning instead.

Parametry

newthis

The object to which the given anonymous function should be bound, or NULL for the closure to be unbound.

newscope

The class scope to which associate the closure is to be associated, or 'static' to keep the current one. If an object is given, the type of the object will be used instead. This determines the visibility of protected and private methods of the bound object.

Zwracane wartości

Returns the newly created Closure object lub FALSE w przypadku niepowodzenia

Przykłady

Przykład #1 Closure::bindTo() example

<?php

class {
    function 
__construct($val) {
        
$this->val $val;
    }
    function 
getClosure() {
        
//returns closure bound to this object and scope
        
return function() { return $this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl $ob1->getClosure();
echo 
$cl(), "\n";
$cl $cl->bindTo($ob2);
echo 
$cl(), "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

1
2

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.

backlog

Used to limit the number of outstanding connections in the socket's listen queue.

Informacja:

This is only applicable to stream_socket_server().

Rejestr zmian

Wersja Opis
5.1.0 Added bindto.
5.3.3 Added backlog.

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.

follow_location integer

Follow Location: .. redirects.

Defaults to TRUE.

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.4 Added follow_location.
5.3.0 The protocol_version supports chunked transfer decoding when set to 1.1.
5.2.10 Added ignore_errors.
5.2.10 The header can now be an numerically indexed array.
5.2.1 Added timeout.
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);

?>

Przykład #2 Ignore redirects but fetch headers and content

<?php

$url 
"http://www.example.org/header.php";

$opts = array('http' =>
    array(
        
'method' => 'GET',
        
'max_redirects' => '0',
        
'ignore_errors' => '1'
    
)
);

$context stream_context_create($opts);
$stream fopen($url'r'false$context);

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>

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.

Informacja: HTTP status line
When this stream wrapper follows a redirect, the wrapper_data returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index 0.

array (
  'wrapper_data' =>
  array (
    0 => 'HTTP/1.0 301 Moved Permantenly',
    1 => 'Cache-Control: no-cache',
    2 => 'Connection: close',
    3 => 'Location: http://example.com/foo.jpg',
    4 => 'HTTP/1.1 200 OK',
    ...
The first request returned a 301 (permanent redirect), so the stream wrapper automatically followed the redirect to get a 200 response (index = 4).



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. Requires verify_peer.

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_cert_chain boolean

If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.

SNI_enabled boolean

If set to TRUE server name indication will be enabled. Enabling SNI allows multiple certificates on the same IP address.

SNI_server_name string

If set, then this value will be used as server name for server name indication. If this value is not set, then the server name is guessed based on the hostname used when opening the stream.

Rejestr zmian

Wersja Opis
5.3.2 Added SNI_enabled and SNI_server_name.
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://.

Informacja: For SNI (Server Name Indication) to be available, then PHP must be compiled with OpenSSL 0.9.8j or greater. Use the OPENSSL_TLSEXT_SERVER_NAME to determine whether SNI is supported.

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.

Parametry

notification callable

A callable to be called when an event occurs on a stream.

See stream_notification_callback() for more details.


Spis treści



Supported Protocols and Wrappers

PHP comes with many built-in wrappers for various URL-style protocols for use with the filesystem functions such as fopen(), copy(), file_exists() and filesize(). In addition to these wrappers, it is possible to register custom wrappers using the stream_wrapper_register() function.

Informacja: The URL syntax used to describe a wrapper only supports the scheme://... syntax. The scheme:/ and scheme: syntaxes are not supported.


file://

file://Accessing local filesystem

Opis

Filesystem is the default wrapper used with PHP and represents the local filesystem. When a relative path is specified (a path which does not begin with /, \, \\, or a Windows drive letter) the path provided will be applied against the current working directory. In many cases this is the directory in which the script resides unless it has been changed. Using the CLI sapi, this defaults to the directory from which the script was called.

With some functions, such as fopen() and file_get_contents(), include_path may be optionally searched for relative paths as well.

Opcje

  • /path/to/file.ext
  • relative/path/to/file.ext
  • fileInCwd.ext
  • C:/path/to/winfile.ext
  • C:\path\to\winfile.ext
  • \\smbserver\share\path\to\winfile.ext
  • file:///path/to/file.ext

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes
Allows Appending Yes
Allows Simultaneous Reading and Writing Yes
Supports stat() Yes
Supports unlink() Yes
Supports rename() Yes
Supports mkdir() Yes
Supports rmdir() Yes

Rejestr zmian

Wersja Opis
5.0.0 Added file://.



http://

https://

http:// -- https://Accessing HTTP(s) URLs

Opis

Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method. A Host: header is sent with the request to handle name-based virtual hosts. If you have configured a user_agent string using your php.ini file or the stream context, it will also be included in the request.

The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable.

If it's important to know the URL of the resource where your document came from (after all redirects have been processed), you'll need to process the series of response headers returned by the stream.

The from directive will be used for the From: header if set and not overwritten by the Context options and parameters.

Opcje

  • http://example.com
  • http://example.com/file.php?var1=val1&var2=val2
  • http://user:password@example.com
  • https://example.com
  • https://example.com/file.php?var1=val1&var2=val2
  • https://user:password@example.com

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen Yes
Allows Reading Yes
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing N/A
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No

Rejestr zmian

Wersja Opis
4.3.7 Detect buggy IIS servers to avoid "SSL: Fatal Protocol Error" errors.
4.3.0 Added https://.
4.0.5 Added support for redirects.

Przykłady

Przykład #1 Detecting which URL we ended up on after redirects

<?php
$url 
'http://www.example.com/redirecting_page.php';

$fp fopen($url'r');

$meta_data stream_get_meta_data($fp);
foreach (
$meta_data['wrapper_data'] as $response) {

    
/* Were we redirected? */
    
if (strtolower(substr($response010)) == 'location: ') {

        
/* update $url with where we were redirected to */
        
$url substr($response10);
    }

}

?>

Przykład #2 Sending custom headers with an HTTP request

Custom headers may be sent using context options. It is also possible to use this hack: Custom headers may be sent with an HTTP request by taking advantage of a side-effect in the handling of the user_agent INI setting. Set user_agent to any valid string (such as the default PHP/version setting) followed by a carriage-return/line-feed pair and any additional headers.

<?php
ini_set
('user_agent'"PHP\r\nX-MyCustomHeader: Foo");

$fp fopen('http://www.example.com/index.php''r');
?>

Results in the following request being sent:

GET /index.php HTTP/1.0
Host: www.example.com
User-Agent: PHP
X-MyCustomHeader: Foo

Notatki

Informacja: HTTPS is only supported when the openssl extension is enabled.

HTTP connections are read-only; writing data or copying files to an HTTP resource is not supported.

Sending POST and PUT requests, for example, can be done with the help of HTTP Contexts.

Zobacz też:



ftp://

ftps://

ftp:// -- ftps://Accessing FTP(s) URLs

Opis

Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail.

You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.

If you have set the from directive in php.ini, then this value will be sent as the anonymous FTP password.

Opcje

  • ftp://example.com/pub/file.txt
  • ftp://user:password@example.com/pub/file.txt
  • ftps://example.com/pub/file.txt
  • ftps://user:password@example.com/pub/file.txt

Opcje

Wrapper Summary
Attribute PHP 4 PHP 5
Restricted by allow_url_fopen Yes Yes
Allows Reading Yes Yes
Allows Writing Yes (new files only) Yes (new files/existing files with overwrite)
Allows Appending No Yes
Allows Simultaneous Reading and Writing No No
Supports stat() No As of PHP 5.0.0: filesize(), filetype(), file_exists(), is_file(), and is_dir() elements only. As of PHP 5.1.0: filemtime().
Supports unlink() No Yes
Supports rename() No Yes
Supports mkdir() No Yes
Supports rmdir() No Yes

Rejestr zmian

Wersja Opis
4.3.0 Added ftps://.

Notatki

Informacja:

FTPS is only supported when the openssl extension is enabled.

If the server does not support SSL, then the connection falls back to regular unencrypted ftp.

Informacja: Appending
As of PHP 5.0.0 files may be appended via the ftp:// URL wrapper. In prior versions, attempting to append to a file via ftp:// will result in failure.

Zobacz też:



php://

php://Accessing various I/O streams

Opis

PHP provides a number of miscellaneous I/O streams that allow access to PHP's own input and output streams, the standard input, output and error file descriptors, in-memory and disk-backed temporary file streams, and filters that can manipulate other file resources as they are read from and written to.

php://stdin, php://stdout and php://stderr

php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the PHP process. The stream references a duplicate file descriptor, so if you open php://stdin and later close it, you close only your copy of the descriptor-the actual stream referenced by STDIN is unaffected. Note that PHP exhibited buggy behavior in this regard until PHP 5.2.1. It is recommended that you simply use the constants STDIN, STDOUT and STDERR instead of manually opening streams using these wrappers.

php://stdin is read-only, whereas php://stdout and php://stderr are write-only.

php://input

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Informacja: A stream opened with php://input can only be read once; the stream does not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.

php://output

php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print() and echo().

php://fd

php://fd allows direct access to the given file descriptor. For example, php://fd/3 refers to file descriptor 3.

php://memory and php://temp

php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.

The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.

php://filter

php://filter is a kind of meta-wrapper designed to permit the application of filters to a stream at the time of opening. This is useful with all-in-one file functions such as readfile(), file(), and file_get_contents() where there is otherwise no opportunity to apply a filter to the stream prior the contents being read.

The php://filter target takes the following parameters as part of its path. Please refer to the examples for specifics on using these parameters.

php://filter parameters
Name Description
resource=<stream to be filtered> This parameter is required. It specifies the stream that you would like to filter.
read=<filter list to apply to read chain> This parameter is optional. One or more filter names can be provided here, separated by the pipe character (|).
write=<filter list to apply to write chain> This parameter is optional. One or more filter names can be provided here, separated by the pipe character (|).
<filter list to apply to both chains> Any filter lists which are not prefixed by read= or write= will be applied to both the read and write chains as appropriate.

Opcje

Wrapper Summary (for php://filter, refer to the summary of the wrapper being filtered)
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include php://input, php://stdin, php://memory and php://temp only.
Allows Reading php://stdin, php://input, php://fd, php://memory and php://temp only.
Allows Writing php://stdout, php://stderr, php://output, php://fd, php://memory and php://temp only.
Allows Appending php://stdout, php://stderr, php://output, php://fd, php://memory and php://temp only. (Equivalent to writing)
Allows Simultaneous Reading and Writing php://fd, php://memory and php://temp only.
Supports stat() php://memory and php://temp only.
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No
Supports stream_select() php://stdin, php://stdout, php://stderr, php://fd and php://temp only.

Rejestr zmian

Wersja Opis
5.3.6 php://fd was added.
5.1.0 php://memory and php://temp were added.
5.0.0 php://filter was added.

Przykłady

Przykład #1 php://temp/maxmemory

This optional parameter allows setting the memory limit before php://temp starts using a temporary file.

<?php
// Set the limit to 5 MB.
$fiveMBs 1024 1024;
$fp fopen("php://temp/maxmemory:$fiveMBs"'r+');

fputs($fp"hello\n");

// Read what we have written.
rewind($fp);
echo 
stream_get_contents($fp);
?>

Przykład #2 php://filter/resource=<stream to be filtered>

This parameter must be located at the end of your php://filter specification and should point to the stream which you want filtered.

<?php
/* This is equivalent to simply:
  readfile("http://www.example.com");
  since no filters are actually specified */

readfile("php://filter/resource=http://www.example.com");
?>

Przykład #3 php://filter/read=<filter list to apply to read chain>

This parameter takes one or more filternames separated by the pipe character |.

<?php
/* This will output the contents of
  www.example.com entirely in uppercase */
readfile("php://filter/read=string.toupper/resource=http://www.example.com");

/* This will do the same as above
  but will also ROT13 encode it */
readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.example.com");
?>

Przykład #4 php://filter/write=<filter list to apply to write chain>

This parameter takes one or more filternames separated by the pipe character |.

<?php
/* This will filter the string "Hello World"
  through the rot13 filter, then write to
  example.txt in the current directory */
file_put_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
?>


zlib://

bzip2://

zip://

zlib:// -- bzip2:// -- zip://Compression Streams

Opis

zlib: PHP 4.0.4 - PHP 4.2.3 (systems with fopencookie only)

compress.zlib:// and compress.bzip2:// PHP 4.3.0 and up

zlib: works like gzopen(), except that the stream can be used with fread() and the other filesystem functions. This is deprecated as of PHP 4.3.0 due to ambiguities with filenames containing ':' characters; use compress.zlib:// instead.

compress.zlib:// and compress.bzip2:// are equivalent to gzopen() and bzopen() respectively, and operate even on systems that do not support fopencookie.

ZIP extension registers zip: wrapper.

Opcje

  • zlib:
  • compress.zlib://
  • compress.bzip2://

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes (except zip://)
Allows Appending Yes (except zip://)
Allows Simultaneous Reading and Writing No
Supports stat() No, use the normal file:// wrapper to stat compressed files.
Supports unlink() No, use the normal file:// wrapper to unlink compressed files.
Supports rename() No
Supports mkdir() No
Supports rmdir() No



data://

data://Data (RFC 2397)

Opis

The data: (» RFC 2397) stream wrapper is available since PHP 5.2.0.

Opcje

  • data://text/plain;base64,

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include Yes
Allows Reading Yes
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No

Przykłady

Przykład #1 Print data:// contents

<?php
// prints "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
?>

Przykład #2 Fetch the media type

<?php
$fp   
fopen('data://text/plain;base64,''r');
$meta stream_get_meta_data($fp);

// prints "text/plain"
echo $meta['mediatype'];
?>


glob://

glob://Find pathnames matching pattern

Opis

The glob: stream wrapper is available since PHP 5.3.0.

Opcje

  • glob://

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include No
Allows Reading No
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No

Przykłady

Przykład #1 Basic usage

<?php
// Loop over all *.php files in ext/spl/examples/ directory
// and print the filename and its size
$it = new DirectoryIterator("glob://ext/spl/examples/*.php");
foreach(
$it as $f) {
    
printf("%s: %.1FK\n"$f->getFilename(), $f->getSize()/1024);
}
?>
tree.php: 1.0K
findregex.php: 0.6K
findfile.php: 0.7K
dba_dump.php: 0.9K
nocvsdir.php: 1.1K
phar_from_dir.php: 1.0K
ini_groups.php: 0.9K
directorytree.php: 0.9K
dba_array.php: 1.1K
class_tree.php: 1.8K


phar://

phar://PHP Archive

Opis

The phar:// stream wrapper is available since PHP 5.3.0. See Phar stream wrapper for detailed description.

Opcje

  • phar://

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include No
Allows Reading Yes
Allows Writing Yes
Allows Appending No
Allows Simultaneous Reading and Writing Yes
Supports stat() Yes
Supports unlink() Yes
Supports rename() Yes
Supports mkdir() Yes
Supports rmdir() Yes

Zobacz też:



ssh2://

ssh2://Secure Shell 2

Opis

ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// PHP 4.3.0 and up (PECL)

Informacja: This wrapper is not enabled by default
In order to use the ssh2.*:// wrappers you must install the » SSH2 extension available from » PECL.

In addition to accepting traditional URI login details, the ssh2 wrappers will also reuse open connections by passing the connection resource in the host portion of the URL.

Opcje

  • ssh2.shell://user:pass@example.com:22/xterm
  • ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
  • ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
  • ssh2.sftp://user:pass@example.com:22/path/to/filename

Opcje

Wrapper Summary
Attribute ssh2.shell ssh2.exec ssh2.tunnel ssh2.sftp ssh2.scp
Restricted by allow_url_fopen Yes Yes Yes Yes Yes
Allows Reading Yes Yes Yes Yes Yes
Allows Writing Yes Yes Yes Yes No
Allows Appending No No No Yes (When supported by server) No
Allows Simultaneous Reading and Writing Yes Yes Yes Yes No
Supports stat() No No No Yes No
Supports unlink() No No No Yes No
Supports rename() No No No Yes No
Supports mkdir() No No No Yes No
Supports rmdir() No No No Yes No

Context options
Name Usage Default
session Preconnected ssh2 resource to be reused  
sftp Preallocated sftp resource to be reused  
methods Key exchange, hostkey, cipher, compression, and MAC methods to use  
callbacks    
username Username to connect as  
password Password to use with password authentication  
pubkey_file Name of public key file to use for authentication  
privkey_file Name of private key file to use for authentication  
env Associate array of environment variables to set  
term Terminal emulation type to request when allocating a pty  
term_width Width of terminal requested when allocating a pty  
term_height Height of terminal requested when allocating a pty  
term_units Units to use with term_width and term_height SSH2_TERM_UNIT_CHARS

Przykłady

Przykład #1 Opening a stream from an active connection

<?php
$session 
ssh2_connect('example.com'22);
ssh2_auth_pubkey_file($session'username''/home/username/.ssh/id_rsa.pub',
                                            
'/home/username/.ssh/id_rsa''secret');
$stream fopen("ssh2.tunnel://$session/remote.example.com:1234"'r');
?>


rar://

rar://RAR

Opis

The wrapper takes the url encoded path to the RAR archive (relative or absolute), an optional asterik (*), an optional number sign (#) and an optional url encoded entry name, as stored in the archive. Specifying an entry name requires the number sign; a leading forward slash in the entry name is optional.

This wrapper can open both files and directories. When opening directories, the asterisk sign forces the directory entries names to be returned unencoded. If it's not specified, they will be returned url encoded – the reason for this is to allow the wrapper to be correctly used with built-in functionality like the RecursiveDirectoryIterator in the presence of file names that seem like url encoded data.

If the pound sign and the entry name part are not included, the root of the archive will be displayed. This differs from regular directories in that the resulting stream will not contain information such as the modification time, as the root directory is not stored in an individual entry in the archive. The usage of the wrapper with RecursiveDirectoryIterator requires the number sign to be included in the URL when accessing the root, so that the URLs of the children may be constructed correctly.

Informacja: This wrapper is not enabled by default
In order to use the rar:// wrapper, you must install the » rar extension available from » PECL.

rar:// Available since PECL rar 3.0.0

Opcje

  • rar://<url encoded archive name>[*][#[<url encoded entry name>]]

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Restricted by allow_url_include No
Allows Reading Yes
Allows Writing No
Allows Appending No
Allows Simultaneous Reading and Writing No
Supports stat() Yes
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No

Context options
Name Usage Default
open_password The password used to encrypt the headers of the archive, if any. WinRAR will encrypt all the files with the same password as the headers password when the later is present, so for archives with encrypted headers, file_password will be ignored.  
file_password The password used to encrypt a file, if any. If the headers are also encrypted, this option will be ignored in favor of open_password. The reason there are two options is to cover the possibility of supporting archives with different headers and file passwords, should those archives arise. Note that if the archive does not have its headers encrypted, open_password will be ignored and this option must be used instead.  
volume_callback A callback to determine the path of missing volumes. See RarArchive::open() for more information.  

Przykłady

Przykład #1 Traversing a RAR archive

<?php

class MyRecDirIt extends RecursiveDirectoryIterator {
    function 
current() {
        return 
rawurldecode($this->getSubPathName()) .
            (
is_dir(parent::current())?" [DIR]":"");
    }
}

$f "rar://" rawurlencode(dirname(__FILE__)) .
    
DIRECTORY_SEPARATOR 'dirs_and_extra_headers.rar#';

$it = new RecursiveTreeIterator(new MyRecDirIt($f));

foreach (
$it as $s) {
    echo 
$s"\n";
}
?>

Powyższy przykład wyświetli coś podobnego do:

|-allow_everyone_ni [DIR]
|-file1.txt
|-file2_אּ.txt
|-with_streams.txt
\-אּ [DIR]
  |-אּ\%2Fempty%2E [DIR]
  | \-אּ\%2Fempty%2E\file7.txt
  |-אּ\empty [DIR]
  |-אּ\file3.txt
  |-אּ\file4_אּ.txt
  \-אּ\אּ_2 [DIR]
    |-אּ\אּ_2\file5.txt
    \-אּ\אּ_2\file6_אּ.txt

Przykład #2 Opening an encrypted file (header encryption)

<?php
$stream 
fopen("rar://" .
    
rawurlencode(dirname(__FILE__)) . DIRECTORY_SEPARATOR .
    
'encrypted_headers.rar' '#encfile1.txt'"r"false,
    
stream_context_create(
        array(
            
'rar' =>
                array(
                    
'open_password' => 'samplepassword'
                
)
            )
        )
    );
var_dump(stream_get_contents($stream));
/* creation and last access date is opt-in in WinRAR, hence most
 * files don't have them */
var_dump(fstat($stream));
?>

Powyższy przykład wyświetli coś podobnego do:

string(26) "Encrypted file 1 contents."
Array
(
    [0] => 0
    [1] => 0
    [2] => 33206
    [3] => 1
    [4] => 0
    [5] => 0
    [6] => 0
    [7] => 26
    [8] => 0
    [9] => 1259550052
    [10] => 0
    [11] => -1
    [12] => -1
    [dev] => 0
    [ino] => 0
    [mode] => 33206
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 26
    [atime] => 0
    [mtime] => 1259550052
    [ctime] => 0
    [blksize] => -1
    [blocks] => -1
)


ogg://

ogg://Audio streams

Opis

Files opened for reading via the ogg:// wrapper are treated as compressed audio encoded using the OGG/Vorbis codec. Similarly, files opened for writing or appending via the ogg:// wrapper are writen as compressed audio data. stream_get_meta_data(), when used on an OGG/Vorbis file opened for reading will return various details about the stream including the vendor tag, any included comments, the number of channels, the sampling rate, and the encoding rate range described by: bitrate_lower, bitrate_upper, bitrate_nominal, and bitrate_window.

ogg:// PHP 4.3.0 and up (PECL)

Informacja: This wrapper is not enabled by default
In order to use the ogg:// wrapper you must install the » OGG/Vorbis extension available from » PECL.

Opcje

  • ogg://soundfile.ogg
  • ogg:///path/to/soundfile.ogg
  • ogg://http://www.example.com/path/to/soundstream.ogg

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes
Allows Appending Yes
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No

Context options
Name Usage Default Mode
pcm_mode PCM encoding to apply while reading, one of: OGGVORBIS_PCM_U8, OGGVORBIS_PCM_S8, OGGVORBIS_PCM_U16_BE, OGGVORBIS_PCM_S16_BE, OGGVORBIS_PCM_U16_LE, and OGGVORBIS_PCM_S16_LE. (8 vs 16 bit, signed or unsigned, big or little endian) OGGVORBIS_PCM_S16_LE Read
rate Sampling rate of input data, expressed in Hz 44100 Write/Append
bitrate When given as an integer, the fixed bitrate at which to encode. (16000 to 131072) When given as a float, the variable bitrate quality to use. (-1.0 to 1.0) 128000 Write/Append
channels The number of audio channels to encode, typically 1 (Mono), or 2 (Stereo). May range as high as 16. 2 Write/Append
comments An array of string values to encode into the track header.   Write/Append

Przykłady



expect://

expect://Process Interaction Streams

Opis

Streams opened via the expect:// wrapper provide access to process'es stdio, stdout and stderr via PTY.

Informacja: This wrapper is not enabled by default
In order to use the expect:// wrapper you must install the » Expect extension available from » PECL.

expect:// PHP 4.3.0 and up (PECL)

Opcje

  • expect://command

Opcje

Wrapper Summary
Attribute Supported
Restricted by allow_url_fopen No
Allows Reading Yes
Allows Writing Yes
Allows Appending Yes
Allows Simultaneous Reading and Writing No
Supports stat() No
Supports unlink() No
Supports rename() No
Supports mkdir() No
Supports rmdir() No

Przykłady


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 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), 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 the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed), hashing may also be taken into consideration. The well-known example for hashing is storing the cryptographic hash of a password in a database, instead of the password itself. See also crypt().

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), crypt($password'$2a$07$usesomesillystringforsalt$'));
$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), crypt($password'$2a$07$usesomesillystringforsalt$'));
$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 an 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.

A worked example of the issues regarding SQL Injection
Image courtesy of » xkcd

Avoidance Techniques

While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.

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

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Perhaps the most controversial change in PHP is when the default value for the PHP directive register_globals went from ON to OFF in PHP » 4.2.0. Reliance on this directive was quite common and many people didn't even know it existed and assumed it's just how PHP works. This page will explain how one can write insecure code with this directive but keep in mind that the directive itself isn't insecure but rather it's the misuse of it.

When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier. It was a difficult decision, but the PHP community decided to disable this directive by default. When on, people use variables yet really don't know for sure where they come from and can only assume. Internal variables that are defined in the script itself get mixed up with request data sent by users and disabling register_globals changes this. Let's demonstrate with an example misuse of register_globals:

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

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.


What are Magic Quotes

Ostrzeżenie

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

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

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

  • 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

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

  • 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

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

Możliwe jest używanie funkcji header() w celu wysłania do przeądarki komunikatu "Wymagana autoryzacja". To powoduje wyświetlenie okna 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 można znaleŸć 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. Więcej informacji znajduje się w dokumencie » 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();
    
$keys implode('|'array_keys($needed_parts));

    
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.

Od PHP 4.3.0, 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: " htmlspecialchars($_SERVER['PHP_AUTH_USER']) . "<br />";
    echo 
"Poprzednio: " htmlspecialchars($_REQUEST['OldAuth']);
    echo 
"<form action='' method='post'>\n";
    echo 
"<input type='hidden' name='SeenBefore' value='1' />\n";
    echo 
"<input type='hidden' name='OldAuth' value=\"" htmlspecialchars($_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 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.

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 using Session Upload Progress.



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; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. 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.

Since PHP 5.2.12, the max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items.

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.

Ostrzeżenie

Since PHP 5.2.12, the max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.



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 Supported Protocols and Wrappers.

Informacja:

W PHP 4.0.3 i starszych, aby używać opakowań URL, należy skonfigurowć PHP z opcją --enable-url-fopen-wrapper .

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.

Aby połączyć się jako użytkowni inny niż 'anonymous', należy określić nazwę uzytkownika (możliwe, że i hasło) w URL, w następujący sposób 'ftp://użytkownik:hasło@ftp.example.com/ścieżka/do/pliku'. (Można używać takiej samej składni aby uzyskać dostęp do plików za pomocą HTTP w czasie wykorzystywania uwierzytelnienia typu Basic.)

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

Ta opcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej opcji nie jest zalecane.


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 5.4.0.
safe_mode_gid "0" PHP_INI_SYSTEM Dostępna od PHP 4.1.0. Usunięta w PHP 5.4.0.
safe_mode_include_dir NULL PHP_INI_SYSTEM Dostępna od PHP 4.1.0. Usunięta w PHP 5.4.0.
safe_mode_exec_dir "" PHP_INI_SYSTEM Usunięta w PHP 5.4.0.
safe_mode_allowed_env_vars "PHP_" PHP_INI_SYSTEM Usunięta w PHP 5.4.0.
safe_mode_protected_env_vars "LD_LIBRARY_PATH" PHP_INI_SYSTEM Usunięta w PHP 5.4.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.

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.

Ostrzeżenie

Ta opcja jest PRZESTARZAŁA od PHP 5.3.0. Używanie tej opcji nie jest zalecane.

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

Patrz także: open_basedir, disable_functions, disable_classes, 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

Spis treści


Introduction

PHP supports a CLI SAPI as of PHP 4.3.0. The main focus of this SAPI is for developing shell applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It is worth mentioning that CLI and CGI are different SAPIs although they do share many of the same behaviors.

The CLI SAPI is enabled by default using --enable-cli , but may be disabled using the --disable-cli option when running ./configure.

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.

As of PHP 5, the CLI binary is distributed in the main folder as php.exe on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a php-win.exe is distributed if PHP is configured using --enable-cli-win32 . This does the same as the CLI version, except that it doesn't output anything and thus provides no console.

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 is available by typing man php in the shell environment.



Differences to other SAPIs

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 it is possible to 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 Defaults to FALSE, as it can be quite hard to read error messages in the shell enviroment when they are cluttered up with uninterpreted HTML tags.
    implicit_flush TRUE In a shell environment, it is usually desirable for output, such as from print(), echo() and friends, to be displayed immediately, and not held in a buffer. Nonetheless, it is still possible to use output buffering to defer or manipulate standard output.
    max_execution_time 0 (unlimited) PHP in a shell environment tends to be used for a much more diverse range of purposes than typical Web-based scripts, and as these can be very long-running, the maximum execution time is set to unlimited.
    register_argc_argv TRUE

    Setting this to TRUE means that scripts executed via the CLI SAPI always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments).

    The PHP variables $argc and $argv are automatically set to the appropriate values when using the CLI SAPI. These values can also be found in the $_SERVER array, for example: $_SERVER['argv'].

    output_buffering FALSE

    Although the php.ini setting is hardcoded to FALSE, the Output buffering functions are available.

    max_input_time FALSE

    The PHP CLI doesn't not support GET, POST or file uploads.

    Informacja:

    These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This limitation is because the values are applied after all configuration files have been parsed. However, their values can be changed during runtime (although this is not sensible for all of them, such as register_argc_argv).

    Informacja:

    It is recommended to set ignore_user_abort for command line scripts. See ignore_user_abort() for more information.

  • To ease working in the shell environment, a number of constants are defined for I/O streams .

  • The CLI SAPI does not change the current directory to the directory of the executed script.

    Przykład #1 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.



Command line options

The list of command line options provided by the PHP binary can be queried at any time 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 <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output 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>.
  --rz <name>      Show information about Zend extension <name>.
  --ri <name>      Show configuration for extension <name>.

Command line options
Option Long Option Description
-a --interactive

Run PHP interactively. For more information, see the Interactive shell section.

-b --bindpath

Bind Path for external FASTCGI Server mode (CGI only).

-C --no-chdir

Do not chdir to the script's directory (CGI only).

-q --no-header

Quiet-mode. Suppress HTTP header output (CGI only).

-T --timing

Measure execution time of script repeated count times (CGI only).

-c --php-ini

Specifies either a directory in which to look for php.ini, or 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 this option is not specified, php.ini is searched for in the default locations.

-n --no-php-ini

Ignore php.ini completely.

-d --define

Set a custom value for any of the configuration directives allowed in php.ini. The syntax is:

 -d configuration_directive[=value]
 

# 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

Parse and execute the specified file. The -f is optional and may be omitted - providing just the filename to execute is sufficient.

Informacja:

To pass arguments to a script, the first argument must be --, otherwise PHP will interpret them as PHP options.

-h and -? --help and --usage Output a list of command line options with one line descriptions of what they do.
-i --info Calls phpinfo(), and prints out the results. If PHP is not working correctly, it is advisable to use the command 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 very large.
-l --syntax-check

Provides a convenient way to perform only 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 the -f to test for fatal errors too.

Informacja:

This option does not work together with the -r option.

-m --modules

Przykład #1 Printing 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

Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present.

Informacja:

Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell.

Przykład #2 Getting a syntax error when using double quotes

$ php -r "$foo = get_defined_constants();"
PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1

Parse error: syntax error, unexpected '=' in Command line code on line 1

The problem here is that 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.

Przykład #3 Using single quotes to prevent the shell's variable substitution

$ 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 using a shell other than sh/bash, further issues might be experienced - if appropriate, a bug report should be opened at » http://bugs.php.net/. It is still easy to run into trouble when trying to use variables (shell or PHP) in commnad-line code, or using backslashes for escaping, so take great care when doing so. You have been warned!

Informacja:

-r is available in the CLI SAPI, but not in the CGI SAPI.

Informacja:

This option is only intended for very basic code, so some configuration directives (such as 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 #4 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 --server

Starts built-in web server. Available as of PHP 5.4.0.

-t --docroot Specifies document root for built-in web server. Available as of PHP 5.4.0.
-s --syntax-highlight and --syntax-highlighting

Display colour syntax highlighted source.

This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code> HTML tags, no HTML headers.

Informacja:

This option does not work together with the -r option.

-v --version

Przykład #5 Using -v to get the SAPI name and the version of PHP and Zend

$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

-w --strip

Display source with comments and whitespace stripped.

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 /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system's library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory.

  --ini

Show configuration file names and scanned directories. Available as of PHP 5.2.3.

Przykład #6 --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

Show 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 #7 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 #8 --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 #9 --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 ] {
    }
  }
}

--rz --rzendextension

Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). Available as of PHP 5.4.0.

--ri --rextinfo

Show 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 is available using "main" as extension name.

Przykład #10 --ri example

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

Informacja:

Options -rBRFEH, --ini and --r[fcezi] are available only in CLI.



Executing PHP files

There are three different ways of supplying the CLI SAPI with PHP code to be executed:

  1. Tell 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. Note that there is no restriction on which files can be executed; in particular, the filename is not required have a .php extension.

    Informacja:

    If arguments need to be passed to the script when using -f , the first argument must be --.

  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 with regard to shell variable substitution and usage of quotes.

    Informacja:

    Read the example carefully: there are no beginning or ending tags! The -r switch simply does not need them, and using them will lead to a parse error.

  3. Provide the PHP code to execute via standard input (stdin).

    This gives the powerful ability to create PHP code dynamically 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.

As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv. The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch -r , the value of $argv[0] will be just a dash (-). The same is true if the code is executed via a pipe from STDIN.

A second global variable, $argc, contains the number of elements in the $argv array (not the number of arguments passed to the script).

As long as the arguments to be passed to the script do not start with the - character, there's nothing special to watch out for. Passing an argument to the script which starts with a - will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every following argument is passed untouched to the 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 the script and prevent PHP from showing its usage
$ php -r 'var_dump($argv);' -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}

However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP CLI binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other 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, it is now possible to 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 can be seen, in this case no special care needs to be taken when passing parameters starting with -.

The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or "shebang") first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it's formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below.

Przykład #2 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];
}
?>

The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a CLI version here, so no HTTP headers will be output.

The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was --help , -help , -h or -? , the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received.

To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task:

Przykład #3 Batch file to run a command line PHP script (script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

Assuming the above program is named script.php, and the CLI php.exe is in C:\php\php.exe, this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h.

See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP.

On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.



Input/output streams

The CLI SAPI defines a few constants for I/O streams to make programming for the command line a bit easier.

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 if reading the PHP script from stdin.



Interactive shell

As of PHP 5.1.0, the CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option.

Using the interactive shell you are able to type PHP code and have it executed directly.

Przykład #1 Executing code using the interactive shell

$ php -a
Interactive shell

php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >

The interactive shell also features tab completion for functions, constants, class names, variables, static method calls and class constants.

Przykład #2 Tab completion

Pressing the tab key twice when there are multiple possible completions will result in a list of these completions:

php > strp[TAB][TAB]
strpbrk   strpos    strptime  
php > strp

When there is only one possible completion, pressing tab once will complete the rest on the same line:

php > strpt[TAB]ime(

Completion will also work for names that have been defined during the current interactive shell session:

php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableName

The interactive shell stores your history which can be accessed using the up and down keys. The history is saved in the ~/.php_history file.

As of PHP 5.4.0, the CLI SAPI provides the php.ini settings cli.pager and cli.prompt. The cli.pager setting allows an external program (such as less) to act as a pager for the output instead of being displayed directly on the screen. The cli.prompt setting makes it possible to change the php > prompt.

In PHP 5.4.0 it was also made possible to set php.ini settings in the interactive shell using a shorthand notation.

Przykład #3 Setting php.ini settings in the interactive shell

The cli.prompt setting:

php > #cli.prompt=hello world :> 
hello world :>

Using backticks it is possible to have PHP code executed in the prompt:

php > #cli.prompt=`echo date('H:i:s');` php > 
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >

Setting the pager to less:

php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >

The cli.prompt setting supports a few escape sequences:

cli.prompt escape sequences
Sequence Description
\e Used for adding colors to the prompt. An example could be \e[032m\v \e[031m\b \e[34m\> \e[0m
\v The PHP version.
\b Indicates which block PHP is in. For instance /* to indicate being inside a multi-line comment. The outer scope is denoted by php.
\> Indicates the prompt character. By default this is >, but changes when the shell is inside an unterminated block or string. Possible characters are: ' " { ( >

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.



Built-in web server

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

This web server is designed for developmental purposes only, and should not be used in production.

URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root.

If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, then a 404 response code is returned.

If a PHP file is given on the command line when the web server is started it is treated as a "router" script for the web server. The script is run at the start of each HTTP request. If this script returns FALSE, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser.

Przykład #1 Starting the web server

$ cd ~/public_html
$ php -S localhost:8000

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
[Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
[Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
[Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
[Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read

Przykład #2 Starting with a specific document root directory

$ cd ~/public_html
$ php -S localhost:8000 -t foo/

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quit

Przykład #3 Using a Router Script

Requests for images will display them, but requests for HTML files will display "Welcome to PHP"

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/'$_SERVER["REQUEST_URI"]))
    return 
false;    // serve the requested resource as-is.
else { 
    echo 
"<p>Welcome to PHP</p>";
}
?>
$ php -S localhost:8000 router.php

After several URI requests the terminal will show something similar to:

PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read
[Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read
[Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read



Garbage Collection

Spis treści

This section explains the merits of the new Garbage Collection (also known as GC) mechanism that is part of PHP 5.3.


Reference Counting Basics

A PHP variable is stored in a container called a "zval". A zval container contains, besides the variable's type and value, two additional bits of information. The first is called "is_ref" and is a boolean value indicating whether or not the variable is part of a "reference set". With this bit, PHP's engine knows how to differentiate between normal variables and references. Since PHP allows user-land references, as created by the & operator, a zval container also has an internal reference counting mechanism to optimize memory usage. This second piece of additional information, called "refcount", contains how many variable names (also called symbols) point to this one zval container. All symbols are stored in a symbol table, of which there is one per scope. There is a scope for the main script (i.e., the one requested through the browser), as well as one for every function or method.

A zval container is created when a new variable is created with a constant value, such as:

Przykład #1 Creating a new zval container

<?php
$a 
"new string";
?>

In this case, the new symbol name, a, is created in the current scope, and a new variable container is created with the type string and the value new string. The "is_ref" bit is by default set to FALSE because no user-land reference has been created. The "refcount" is set to 1 as there is only one symbol that makes use of this variable container. Note that if "refcount" is 1, "is_ref" is always FALSE. If you have » Xdebug installed, you can display this information by calling xdebug_debug_zval().

Przykład #2 Displaying zval information

<?php
xdebug_debug_zval
('a');
?>

Powyższy przykład wyświetli:

a: (refcount=1, is_ref=0)='new string'

Assigning this variable to another variable name will increase the refcount.

Przykład #3 Increasing refcount of a zval

<?php
$a 
"new string";
$b $a;
xdebug_debug_zval'a' );
?>

Powyższy przykład wyświetli:

a: (refcount=2, is_ref=0)='new string'

The refcount is 2 here, because the same variable container is linked with both a and b. PHP is smart enough not to copy the actual variable container when it is not necessary. Variable containers get destroyed when the "refcount" reaches zero. The "refcount" gets decreased by one when any symbol linked to the variable container leaves the scope (e.g. when the function ends) or when unset() is called on a symbol. The following example shows this:

Przykład #4 Decreasing zval refcount

<?php
$a 
"new string";
$c $b $a;
xdebug_debug_zval'a' );
unset( 
$b$c );
xdebug_debug_zval'a' );
?>

Powyższy przykład wyświetli:

a: (refcount=3, is_ref=0)='new string'
a: (refcount=1, is_ref=0)='new string'

If we now call unset($a);, the variable container, including the type and value, will be removed from memory.

Compound Types

Things get a tad more complex with compound types such as arrays and objects. Instead of a scalar value, arrays and objects store their properties in a symbol table of their own. This means that the following example creates three zval containers:

Przykład #5 Creating a array zval

<?php
$a 
= array( 'meaning' => 'life''number' => 42 );
xdebug_debug_zval'a' );
?>

Powyższy przykład wyświetli coś podobnego do:

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=1, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42
)

Or graphically

Zvals for a simple array

The three zval containers are: a, meaning, and number. Similar rules apply for increasing and decreasing "refcounts". Below, we add another element to the array, and set its value to the contents of an already existing element:

Przykład #6 Adding already existing element to an array

<?php
$a 
= array( 'meaning' => 'life''number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval'a' );
?>

Powyższy przykład wyświetli coś podobnego do:

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=2, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42,
   'life' => (refcount=2, is_ref=0)='life'
)

Or graphically

Zvals for a simple array with a reference

From the above Xdebug output, we see that both the old and new array elements now point to a zval container whose "refcount" is 2. Although Xdebug's output shows two zval containers with value 'life', they are the same one. The xdebug_debug_zval() function does not show this, but you could see it by also displaying the memory pointer.

Removing an element from the array is like removing a symbol from a scope. By doing so, the "refcount" of a container that an array element points to is decreased. Again, when the "refcount" reaches zero, the variable container is removed from memory. Again, an example to show this:

Przykład #7 Removing an element from an array

<?php
$a 
= array( 'meaning' => 'life''number' => 42 );
$a['life'] = $a['meaning'];
unset( 
$a['meaning'], $a['number'] );
xdebug_debug_zval'a' );
?>

Powyższy przykład wyświetli coś podobnego do:

a: (refcount=1, is_ref=0)=array (
   'life' => (refcount=1, is_ref=0)='life'
)

Now, things get interesting if we add the array itself as an element of the array, which we do in the next example, in which we also sneak in a reference operator, since otherwise PHP would create a copy:

Przykład #8 Adding the array itself as an element of it self

<?php
$a 
= array( 'one' );
$a[] =& $a;
xdebug_debug_zval'a' );
?>

Powyższy przykład wyświetli coś podobnego do:

a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

Or graphically

Zvals for an array with a circular reference

You can see that the array variable (a) as well as the second element (1) now point to a variable container that has a "refcount" of 2. The "..." in the display above shows that there is recursion involved, which, of course, in this case means that the "..." points back to the original array.

Just like before, unsetting a variable removes the symbol, and the reference count of the variable container it points to is decreased by one. So, if we unset variable $a after running the above code, the reference count of the variable container that $a and element "1" point to gets decreased by one, from "2" to "1". This can be represented as:

Przykład #9 Unsetting $a

(refcount=1, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=1, is_ref=1)=...
)

Or graphically

Zvals after removal of array with a circular reference demonstrating the memory leak

Cleanup Problems

Although there is no longer a symbol in any scope pointing to this structure, it cannot be cleaned up because the array element "1" still points to this same array. Because there is no external symbol pointing to it, there is no way for a user to clean up this structure; thus you get a memory leak. Fortunately, PHP will clean up this data structure at the end of the request, but before then, this is taking up valuable space in memory. This situation happens often if you're implementing parsing algorithms or other things where you have a child point back at a "parent" element. The same situation can also happen with objects of course, where it actually is more likely to occur, as objects are always implicitly used by reference.

This might not be a problem if this only happens once or twice, but if there are thousands, or even millions, of these memory losses, this obviously starts being a problem. This is especially problematic in long running scripts, such as daemons where the request basically never ends, or in large sets of unit tests. The latter caused problems while running the unit tests for the Template component of the eZ Components library. In some cases, it would require over 2 GB of memory, which the test server didn't quite have.



Collecting Cycles

Traditionally, reference counting memory mechanisms, such as that used previously by PHP, fail to address circular reference memory leaks. As of 5.3.0 PHP however implements the synchronous algorithm from the » Concurrent Cycle Collection in Reference Counted Systems paper which addresses that issue.

A full explanation of how the algorithm works would be slightly beyond the scope of this section, but the basics are explained here. First of all, we have to establish a few ground rules. If a refcount is increased, it's still in use and therefore, not garbage. If the refcount is decreased and hits zero, the zval can be freed. This means that garbage cycles can only be created when a refcount argument is decreased to a non-zero value. Secondly, in a garbage cycle, it is possible to discover which parts are garbage by checking whether it is possible to decrease their refcount by one, and then checking which of the zvals have a refcount of zero.

Garbage collection algorithm

To avoid having to call the checking of garbage cycles with every possible decrease of a refcount, the algorithm instead puts all possible roots (zvals) in the "root buffer" (marking them "purple"). It also makes sure that each possible garbage root ends up in the buffer only once. Only when the root buffer is full does the collection mechanism start for all the different zvals inside. See step A in the figure above.

In step B, the algorithm runs a depth-first search on all possible roots to decrease by one the refcounts of each zval it finds, making sure not to decrease a refcount on the same zval twice (by marking them as "grey"). In step C, the algorithm again runs a depth-first search from each root node, to check the refcount of each zval again. If it finds that the refcount is zero, the zval is marked "white" (blue in the figure). If it's larger than zero, it reverts the decreasing of the refcount by one with a depth-first search from that point on, and they are marked "black" again. In the last step (D), the algorithm walks over the root buffer removing the zval roots from there, and meanwhile, checks which zvals have been marked "white" in the previous step. Every zval marked as "white" will be freed.

Now that you have a basic understanding of how the algorithm works, we will look back at how this integrates with PHP. By default, PHP's garbage collector is turned on. There is, however, a php.ini setting that allows you to change this: zend.enable_gc .

When the garbage collector is turned on, the cycle-finding algorithm as described above is executed whenever the root buffer runs full. The root buffer has a fixed size of 10,000 possible roots (although you can alter this by changing the GC_ROOT_BUFFER_MAX_ENTRIES constant in Zend/zend_gc.c in the PHP source code, and re-compiling PHP). When the garbage collector is turned off, the cycle-finding algorithm will never run. However, possible roots will always be recorded in the root buffer, no matter whether the garbage collection mechanism has been activated with this configuration setting.

If the root buffer becomes full with possible roots while the garbage collection mechanism is turned off, further possible roots will simply not be recorded. Those possible roots that are not recorded will never be analyzed by the algorithm. If they were part of a circular reference cycle, they would never be cleaned up and would create a memory leak.

The reason why possible roots are recorded even if the mechanism has been disabled is because it's faster to record possible roots than to have to check whether the mechanism is turned on every time a possible root could be found. The garbage collection and analysis mechanism itself, however, can take a considerable amount of time.

Besides changing the zend.enable_gc configuration setting, it is also possible to turn the garbage collecting mechanism on and off by calling gc_enable() or gc_disable() respectively. Calling those functions has the same effect as turning on or off the mechanism with the configuration setting. It is also possible to force the collection of cycles even if the possible root buffer is not full yet. For this, you can use the gc_collect_cycles() function. This function will return how many cycles were collected by the algorithm.

The rationale behind the ability to turn the mechanism on and off, and to initiate cycle collection yourself, is that some parts of your application could be highly time-sensitive. In those cases, you might not want the garbage collection mechanism to kick in. Of course, by turning off the garbage collection for certain parts of your application, you do risk creating memory leaks because some possible roots might not fit into the limited root buffer. Therefore, it is probably wise to call gc_collect_cycles() just before you call gc_disable() to free up the memory that could be lost through possible roots that are already recorded in the root buffer. This then leaves an empty buffer so that there is more space for storing possible roots while the cycle collecting mechanism is turned off.



Performance Considerations

We have already mentioned in the previous section that simply collecting the possible roots had a very tiny performance impact, but this is when you compare PHP 5.2 against PHP 5.3. Although the recording of possible roots compared to not recording them at all, like in PHP 5.2, is slower, other changes to the PHP runtime in PHP 5.3 prevented this particular performance loss from even showing.

There are two major areas in which performance is affected. The first area is reduced memory usage, and the second area is run-time delay when the garbage collection mechanism performs its memory cleanups. We will look at both of those issues.

Reduced Memory Usage

First of all, the whole reason for implementing the garbage collection mechanism is to reduce memory usage by cleaning up circular-referenced variables as soon as the prerequisites are fulfilled. In PHP's implementation, this happens as soon as the root-buffer is full, or when the function gc_collect_cycles() is called. In the graph below, we display the memory usage of the script below, in both PHP 5.2 and PHP 5.3, excluding the base memory that PHP itself uses when starting up.

Przykład #1 Memory usage example

<?php
class Foo
{
    public 
$var '3.1415962654';
}

$baseMemory memory_get_usage();

for ( 
$i 0$i <= 100000$i++ )
{
    
$a = new Foo;
    
$a->self $a;
    if ( 
$i 500 === )
    {
        echo 
sprintf'%8d: '$i ), memory_get_usage() - $baseMemory"\n";
    }
}
?>
Comparison of memory usage between PHP 5.2 and PHP 5.3

In this very academic example, we are creating an object in which a property is set to point back to the object itself. When the $a variable in the script is re-assigned in the next iteration of the loop, a memory leak would typically occur. In this case, two zval-containers are leaked (the object zval, and the property zval), but only one possible root is found: the variable that was unset. When the root-buffer is full after 10,000 iterations (with a total of 10,000 possible roots), the garbage collection mechanism kicks in and frees the memory associated with those possible roots. This can very clearly be seen in the jagged memory-usage graph for PHP 5.3. After each 10,000 iterations, the mechanism kicks in and frees the memory associated with the circular referenced variables. The mechanism itself does not have to do a whole lot of work in this example, because the structure that is leaked is extremely simple. From the diagram, you see that the maximum memory usage in PHP 5.3 is about 9 Mb, whereas in PHP 5.2 the memory usage keeps increasing.

Run-Time Slowdowns

The second area where the garbage collection mechanism influences performance is the time taken when the garbage collection mechanism kicks in to free the "leaked" memory. In order to see how much this is, we slightly modify the previous script to allow for a larger number of iterations and the removal of the intermediate memory usage figures. The second script is here:

Przykład #2 GC performance influences

<?php
class Foo
{
    public 
$var '3.1415962654';
}

for ( 
$i 0$i <= 1000000$i++ )
{
    
$a = new Foo;
    
$a->self $a;
}

echo 
memory_get_peak_usage(), "\n";
?>

We will run this script two times, once with the zend.enable_gc setting turned on, and once with it turned off:

Przykład #3 Running the above script

time php -dzend.enable_gc=0 -dmemory_limit=-1 -n example2.php
# and
time php -dzend.enable_gc=1 -dmemory_limit=-1 -n example2.php

On my machine, the first command seems to take consistently about 10.7 seconds, whereas the second command takes about 11.4 seconds. This is a slowdown of about 7%. However, the maximum amount of memory used by the script is reduced by 98% from 931Mb to 10Mb. This benchmark is not very scientific, or even representative of real-life applications, but it does demonstrate the memory usage benefits that this garbage collection mechanism provides. The good thing is that the slowdown is always the same 7%, for this particular script, while the memory saving capabilities save more and more memory as more circular references are found during script execution.

PHP's Internal GC Statistics

It is possible to coax a little bit more information about how the garbage collection mechanism is run from within PHP. But in order to do so, you will have to re-compile PHP to enable the benchmark and data-collecting code. You will have to set the CFLAGS environment variable to -DGC_BENCH=1 prior to running ./configure with your desired options. The following sequence should do the trick:

Przykład #4 Recompiling PHP to enable GC benchmarking

export CFLAGS=-DGC_BENCH=1
./config.nice
make clean
make

When you run the above example code again with the newly built PHP binary, you will see the following being shown after PHP has finished execution:

Przykład #5 GC statistics

GC Statistics
-------------
Runs:               110
Collected:          2072204
Root buffer length: 0
Root buffer peak:   10000

      Possible            Remove from  Marked
        Root    Buffered     buffer     grey
      --------  --------  -----------  ------
ZVAL   7175487   1491291    1241690   3611871
ZOBJ  28506264   1527980     677581   1025731

The most informative statistics are displayed in the first block. You can see here that the garbage collection mechanism ran 110 times, and in total, more than 2 million memory allocations were freed during those 110 runs. As soon as the garbage collection mechanism has run at least one time, the "Root buffer peak" is always 10000.

Conclusion

In general the garbage collector in PHP will only cause a slowdown when the cycle collecting algorithm actually runs, whereas in normal (smaller) scripts there should be no performance hit at all.

However, in the cases where the cycle collection mechanism does run for normal scripts, the memory reduction it will provide allows more of those scripts to run concurrently on your server, since not so much memory is used in total.

The benefits are most apparent for longer-running scripts, such as lengthy test suites or daemon scripts. Also, for » PHP-GTK applications that generally tend to run longer than scripts for the Web, the new mechanism should make quite a bit of a difference regarding memory leaks creeping in over time.





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 the TMP, TEMP and 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.

When APC is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APC is built with SHM (SysV Shared Memory) support that uses multiple memory segments. MMAP does not have a maximum limit like SHM does in /proc/sys/kernel/shmmax. In general MMAP support is recommeded because it will reclaim the memory faster when the webserver is restarted and all in all reduces memory allocation impact at startup.

APC configuration options
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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 "32M" 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 "1" PHP_INI_SYSTEM Available since APC 3.0.0. Prior to APC 3.1.4, the default value was "0" (disabled).
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.use_request_time "1" PHP_INI_ALL Available since APC 3.1.3.
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.rfc1867_ttl "3600" PHP_INI_SYSTEM Available since APC 3.1.1.
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.
apc.preload_path NULL PHP_INI_SYSTEM Available since APC 3.1.1.
apc.file_md5 "0" PHP_INI_SYSTEM Available since APC 3.1.1.
apc.canonicalize "1" PHP_INI_SYSTEM Available since APC 3.1.1.
apc.lazy_functions 0 PHP_INI_SYSTEM Available since APC 3.1.3.
apc.lazy_classes 0 PHP_INI_SYSTEM Available since APC 3.1.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.

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.

Ostrzeżenie

This feature is EXPERIMENTAL. The behaviour of this directive, its name, and surrounding documentation may change without notice in a future release of APC. This feature should be used at your own risk.

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.

Note that the rate is only available once all file transfers are completed.

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.rfc1867_ttl bool

TTL for rfc1867 entries.

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.

apc.canonicalize bool

If on, then relative paths are canonicalized in no-stat mode. If set, then files included via stream wrappers can not be cached as realpath() does not support stream wrappers.

apc.preload_path string

apc.use_request_time bool

Use the SAPI request start time for TTL.

apc.file_md5 bool

Records a md5 hash of files.

apc.lazy_functions integer

Enables lazy loading for functions.

apc.lazy_classes integer

Enables lazy loading for classes.



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.

APC_BIN_VERIFY_CRC32 (integer)
APC_BIN_VERIFY_MD5 (integer)
APC_ITER_ALL (integer)
APC_ITER_ATIME (integer)
APC_ITER_CTIME (integer)
APC_ITER_DEVICE (integer)
APC_ITER_DTIME (integer)
APC_ITER_FILENAME (integer)
APC_ITER_INODE (integer)
APC_ITER_KEY (integer)
APC_ITER_MD5 (integer)
APC_ITER_MEM_SIZE (integer)
APC_ITER_MTIME (integer)
APC_ITER_NONE (integer)
APC_ITER_NUM_HITS (integer)
APC_ITER_REFCOUNT (integer)
APC_ITER_TTL (integer)
APC_ITER_TYPE (integer)
APC_ITER_VALUE (integer)
APC_LIST_ACTIVE (integer)
APC_LIST_DELETED (integer)



APC Funkcje


apc_add

(PECL apc >= 3.0.13)

apc_add Cache a new variable in the data store

Opis

bool apc_add ( string $key [, mixed $var [, int $ttl = 0 ]] )
array apc_add ( array $values [, mixed $unused [, 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. keys 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.).

values

Names in key, variables in value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Second syntax returns array with error keys.

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_bin_dump

(PECL apc >= 3.1.4)

apc_bin_dumpGet a binary dump of the given files and user variables

Opis

string apc_bin_dump ([ array $files [, array $user_vars ]] )

Returns a binary dump of the given files and user variables from the APC cache. A NULL for files or user_vars signals a dump of every entry, whereas array() will dump nothing.

Parametry

files

The files. Passing in NULL signals a dump of every entry, while passing in array() will dump nothing.

user_vars

The user vars. Passing in NULL signals a dump of every entry, while passing in array() will dump nothing.

Zwracane wartości

Returns a binary dump of the given files and user variables from the APC cache, FALSE if APC is not enabled, or NULL if an unknown error is encountered.

Zobacz też:



apc_bin_dumpfile

(PECL apc >= 3.1.4)

apc_bin_dumpfileOutput a binary dump of cached files and user variables to a file

Opis

int apc_bin_dumpfile ( array $files , array $user_vars , string $filename [, int $flags = 0 [, resource $context ]] )

Outputs a binary dump of the given files and user variables from the APC cache to the named file.

Parametry

files

The file names being dumped.

user_vars

The user variables being dumped.

filename

The filename where the dump is being saved.

flags

Flags passed to the filename stream. See the file_put_contents() documentation for details.

context

The context passed to the filename stream. See the file_put_contents() documentation for details.

Zwracane wartości

The number of bytes written to the file, otherwise FALSE if APC is not enabled, filename is an invalid file name, filename can't be opened, the file dump can't be completed (e.g., the hard drive is out of disk space), or an unknown error was encountered.

Zobacz też:



apc_bin_load

(PECL apc >= 3.1.4)

apc_bin_loadLoad a binary dump into the APC file/user cache

Opis

bool apc_bin_load ( string $data [, int $flags = 0 ] )

Loads the given binary dump into the APC file/user cache.

Parametry

data

The binary dump being loaded, likely from apc_bin_dump().

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Zwracane wartości

Returns TRUE if the binary dump data was loaded with success, otherwise FALSE is returned. FALSE is returned if APC is not enabled, or if the data is not a valid APC binary dump (e.g., unexpected size).

Przykłady

Przykład #1 apc_bin_load() example

<?php
$data 
apc_bin_dump(NULLNULL);
apc_bin_load($dataAPC_BIN_VERIFY_MD5 APC_BIN_VERIFY_CRC32);
?>

Zobacz też:



apc_bin_loadfile

(PECL apc >= 3.1.4)

apc_bin_loadfileLoad a binary dump from a file into the APC file/user cache

Opis

bool apc_bin_loadfile ( string $filename [, resource $context [, int $flags ]] )

Loads a binary dump from a file into the APC file/user cache.

Parametry

filename

The file name containing the dump, likely from apc_bin_dumpfile().

context

The files context.

flags

Either APC_BIN_VERIFY_CRC32, APC_BIN_VERIFY_MD5, or both.

Zwracane wartości

Returns TRUE on success, otherwise FALSE Reasons it may return FALSE include APC is not enabled, filename is an invalid file name or empty, filename can't be opened, the file dump can't be completed, or if the data is not a valid APC binary dump (e.g., unexpected size).

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.

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.

Zwracane wartości

Array of cached data (and meta-data) lub FALSE w przypadku niepowodzenia

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.

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

Zobacz też:



apc_cas

(PECL apc >= 3.1.1)

apc_casUpdates an old value with a new value

Opis

bool apc_cas ( string $key , int $old , int $new )

apc_cas() updates an already existing integer value if the old parameter matches the currently stored value with the value of the new parameter.

Parametry

key

The key of the value being updated.

old

The old value (the value currently stored).

new

The new value to update to.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 apc_cas() example

<?php
apc_store
('foobar'2);
echo 
'$foobar = 2'PHP_EOL;
echo 
'$foobar == 1 ? 2 : 1 = ', (apc_cas('foobar'12) ? 'ok' 'fail'), PHP_EOL;
echo 
'$foobar == 2 ? 1 : 2 = ', (apc_cas('foobar'21) ? 'ok' 'fail'), PHP_EOL;

echo 
'$foobar = 'apc_fetch('foobar'), PHP_EOL;

echo 
'$f__bar == 1 ? 2 : 1 = ', (apc_cas('f__bar'12) ? 'ok' 'fail'), PHP_EOL;

apc_store('perfection''xyz');
echo 
'$perfection == 2 ? 1 : 2 = ', (apc_cas('perfection'21) ? 'ok' 'epic fail'), PHP_EOL;

echo 
'$foobar = 'apc_fetch('foobar'), PHP_EOL;
?>

Powyższy przykład wyświetli coś podobnego do:

$foobar = 2
$foobar == 1 ? 2 : 1 = fail
$foobar == 2 ? 1 : 2 = ok
$foobar = 1
$f__bar == 1 ? 2 : 1 = fail
$perfection == 2 ? 1 : 2 = epic fail
$foobar = 1

Zobacz też:



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.

Parametry

cache_type

If cache_type is "user", the user cache will be cleared; otherwise, the system cache (cached files) will be cleared.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



apc_compile_file

(PECL apc >= 3.0.13)

apc_compile_file Stores a file in the bytecode cache, bypassing all filters.

Opis

mixed apc_compile_file ( string $filename [, bool $atomic = true ] )

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.

Zobacz też:



apc_dec

(PECL apc >= 3.1.1)

apc_decDecrease a stored number

Opis

int apc_dec ( string $key [, int $step = 1 [, bool &$success ]] )

Decreases a stored integer value.

Parametry

key

The key of the value being decreased.

step

The step, or value to decrease.

success

Optionally pass the success or fail boolean value to this referenced variable.

Zwracane wartości

Returns the current value of key's value on success, lub FALSE w przypadku niepowodzenia

Przykłady

Przykład #1 apc_dec() example

<?php
echo "Let's do something with success"PHP_EOL;

apc_store('anumber'42);

echo 
apc_fetch('anumber'), PHP_EOL;

echo 
apc_dec('anumber'), PHP_EOL;
echo 
apc_dec('anumber'10), PHP_EOL;
echo 
apc_dec('anumber'10$success), PHP_EOL;

var_dump($success);

echo 
"Now, let's fail"PHP_EOLPHP_EOL;

apc_store('astring''foo');

$ret apc_dec('astring'1$fail);

var_dump($ret);
var_dump($fail);
?>

Powyższy przykład wyświetli coś podobnego do:

Let's do something with success
42
41
31
21
bool(true)

Now, let's fail
bool(false)
bool(false)

Zobacz też:



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_file

(PECL apc >= 3.1.1)

apc_delete_fileDeletes files from the opcode cache

Opis

mixed apc_delete_file ( mixed $keys )

Deletes the given files from the opcode cache.

Parametry

keys

The files to be deleted. Accepts a string, array of strings, or an APCIterator object.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Or if keys is an array, then an empty array is returned on success, or an array of failed files is returned.

Przykłady

Przykład #1 apc_delete_file() example

<?php
$filename 
'file.php';

if (
apc_compile_file($filename)) {

    if (
apc_delete_file($filename)) {
        echo 
"Successfully deleted file $filename from APC cache."PHP_EOL;
    }
}

if (
apc_compile_file($filename)) {

    if (
$good apc_delete_file(array($filename'donotexist.php'))) {
        
var_dump($good);
    }
}

$bad apc_delete_file('donotexist.php');
var_dump($bad);
?>

Powyższy przykład wyświetli coś podobnego do:

Successfully deleted file file.php from APC cache.
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 13.
array(1) {
  [0]=>
  string(14) "donotexist.php"
}
[Mon May 24 09:30:33 2010] [apc-warning] Could not stat file donotexist.php, unable to delete from cache. in /tmp/test.php on line 18.
bool(false)

Zobacz też:



apc_delete

(PECL apc >= 3.0.0)

apc_delete Removes a stored variable from the cache

Opis

mixed 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_exists

(PECL apc >= 3.1.4)

apc_existsChecks if APC key exists

Opis

mixed apc_exists ( mixed $keys )

Checks if one ore more APC keys exist.

Parametry

keys

A string, or an array of strings, that contain keys.

Zwracane wartości

Returns TRUE if the key exists, otherwise FALSE Or if an array was passed to keys, then an array is returned that contains all existing keys, or an empty array if none exist.

Przykłady

Przykład #1 apc_exists() example

<?php
$fruit  
'apple';
$veggie 'carrot';

apc_store('foo'$fruit);
apc_store('bar'$veggie);

if (
apc_exists('foo')) {
    echo 
"Foo exists: ";
    echo 
apc_fetch('foo');
} else {
    echo 
"Foo does not exist";
}

echo 
PHP_EOL;
if (
apc_exists('baz')) {
    echo 
"Baz exists.";
} else {
    echo 
"Baz does not exist";
}

echo 
PHP_EOL;

$ret apc_exists(array('foo''donotexist''bar'));
var_dump($ret);

?>

Powyższy przykład wyświetli coś podobnego do:

Foo exists: apple
Baz does not exist
array(2) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  bool(true)
}

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"

Rejestr zmian

Wersja Opis
3.0.17 The success parameter was added.

Zobacz też:



apc_inc

(PECL apc >= 3.1.1)

apc_incIncrease a stored number

Opis

int apc_inc ( string $key [, int $step = 1 [, bool &$success ]] )

Increases a stored number.

Parametry

key

The key of the value being increased.

step

The step, or value to increase.

success

Optionally pass the success or fail boolean value to this referenced variable.

Zwracane wartości

Returns the current value of key's value on success, lub FALSE w przypadku niepowodzenia

Przykłady

Przykład #1 apc_inc() example

<?php
echo "Let's do something with success"PHP_EOL;

apc_store('anumber'42);

echo 
apc_fetch('anumber'), PHP_EOL;

echo 
apc_inc('anumber'), PHP_EOL;
echo 
apc_inc('anumber'10), PHP_EOL;
echo 
apc_inc('anumber'10$success), PHP_EOL;

var_dump($success);

echo 
"Now, let's fail"PHP_EOLPHP_EOL;

apc_store('astring''foo');

$ret apc_inc('astring'1$fail);

var_dump($ret);
var_dump($fail);
?>

Powyższy przykład wyświetli coś podobnego do:

42
43
53
63
bool(true)
Now, let's fail

bool(false)
bool(false)

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 ] )
array apc_store ( array $values [, mixed $unused [, 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. keys 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.).

values

Names in key, variables in value.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu. Second syntax returns array with error keys.

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ż:

  • apc_add() - Cache a new variable in the data store
  • apc_fetch() - Fetch a stored variable from the cache
  • apc_delete() - Removes a stored variable from the cache


Spis treści



The APCIterator class

(PECL apc >= 3.1.1)

Wstęp

The APCIterator class makes it easier to iterate over large APC caches. This is helpful as it allows iterating over large caches in steps, while grabbing a defined number of entries per lock instance, so it frees the cache locks for other activities rather than hold up the entire cache to grab 100 (the default) entries. Also, using regular expression matching is more efficient as it's been moved to the C level.

Krótki opis klasy

APCIterator implements Iterator , Traversable {
/* Methods */
public __construct ( string $cache [, mixed $search = null [, int $format [, int $chunk_size = 100 [, int $list ]]]] )
public mixed current ( void )
public int getTotalCount ( void )
public int getTotalHits ( void )
public int getTotalSize ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void valid ( void )
}

APCIterator::__construct

(PECL apc >= 3.1.1)

APCIterator::__constructConstructs an APCIterator iterator object

Opis

public APCIterator::__construct ( string $cache [, mixed $search = null [, int $format [, int $chunk_size = 100 [, int $list ]]]] )

Constructs an APCIterator object.

Parametry

cache

The cache type, which will be user or file.

search

A PCRE regular expression that matches against APC key names, either as a string for a single regular expression, or as an array of regular expressions. Or, optionally pass in NULL to skip the search.

format

The desired format, as configured with one ore more of the APC_ITER_* constants.

chunk_size

The chunk size. Must be a value greater than 0. The default value is 100.

list

The type to list. Either pass in APC_LIST_ACTIVE or APC_LIST_DELETED.

Zwracane wartości

An APCIterator object on success, or NULL on failure.

Przykłady

Przykład #1 A APCIterator::__construct() example

<?php
foreach (new APCIterator('user''/^counter\./') as $counter) {
    echo 
"$counter[key]$counter[value]\n";
    
apc_dec($counter['key'], $counter['value']);
}
?>

Zobacz też:



APCIterator::current

(PECL apc >= 3.1.1)

APCIterator::currentGet current item

Opis

public mixed APCIterator::current ( void )

Gets the current item from the APCIterator stack.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the current item on success, or FALSE if no more items or exist, or on failure.

Zobacz też:



APCIterator::getTotalCount

(PECL apc >= 3.1.1)

APCIterator::getTotalCountGet total count

Opis

public int APCIterator::getTotalCount ( void )

Get the total count.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The total count.

Zobacz też:



APCIterator::getTotalHits

(PECL apc >= 3.1.1)

APCIterator::getTotalHitsGet total cache hits

Opis

public int APCIterator::getTotalHits ( void )

Gets the total number of cache hits.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The number of hits on success, or FALSE on failure.

Zobacz też:



APCIterator::getTotalSize

(PECL apc >= 3.1.1)

APCIterator::getTotalSizeGet total cache size

Opis

public int APCIterator::getTotalSize ( void )

Gets the total cache size.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

The total cache size.

Zobacz też:



APCIterator::key

(PECL apc >= 3.1.1)

APCIterator::keyGet iterator key

Opis

public string APCIterator::key ( void )

Gets the current iterator key.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the key on success, or FALSE upon failure.

Zobacz też:



APCIterator::next

(PECL apc >= 3.1.1)

APCIterator::nextMove pointer to next item

Opis

public void APCIterator::next ( void )

Moves the iterator pointer to the next element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:



APCIterator::rewind

(PECL apc >= 3.1.1)

APCIterator::rewindRewinds iterator

Opis

public void APCIterator::rewind ( void )

Rewinds back the iterator to the first element.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:



APCIterator::valid

(PECL apc >= 3.1.1)

APCIterator::validChecks if current position is valid

Opis

public void APCIterator::valid ( void )

Checks if the current iterator position is valid.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current iterator position is valid, otherwise FALSE.

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

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/apd.

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
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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:

    <?php
    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 comma 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

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/bcompiler.

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

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 a 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 a 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
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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 On (the default), this parameter will show a report of memory leaks detected by the Zend memory manager. This report will be send to stderr on Posix platforms. On Windows, it will be send to the debugger using OutputDebugString(), and can be viewed with tools like » DbgView. This parameter only has effect in a debug build, 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.  
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.  
64 E_COMPILE_ERROR (integer) Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.  
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.  
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().  
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().  
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().  
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 but not included in E_ALL until PHP 5.4.0
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
32767 E_ALL (integer) All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0. 32767 in PHP 5.4.x, 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 if 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 ([ int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT [, int $limit = 0 ]] )

debug_backtrace() generates a PHP backtrace.

Parametry

options

As of 5.3.6, this parameter is a bitmask for the following options:

debug_backtrace() options
DEBUG_BACKTRACE_PROVIDE_OBJECT Whether or not to populate the "object" index.
DEBUG_BACKTRACE_IGNORE_ARGS Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory.
Before 5.3.6, the only values recognized are TRUE or FALSE, which are the same as setting or not setting the DEBUG_BACKTRACE_PROVIDE_OBJECT option respectively.

limit

As of 5.4.0, this parameter can be used to limit the number of stack frames returned. By default (limit=0) it returns all stack frames.

Zwracane wartości

Returns an array of associative arrays. 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.4.0 Added the optional parameter limit.
5.3.6 The parameter provide_object changed to options and additional option DEBUG_BACKTRACE_IGNORE_ARGS is added.
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 ([ int $options = 0 [, int $limit = 0 ]] )

debug_print_backtrace() prints a PHP backtrace. It prints the function calls, included/required files and eval()ed stuff.

Parametry

options

As of 5.3.6, this parameter is a bitmask for the following options:

debug_print_backtrace() options
DEBUG_BACKTRACE_IGNORE_ARGS Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory.

limit

As of 5.4.0, this parameter can be used to limit the number of stack frames printed. By default (limit=0) it prints all stack frames.

Zwracane wartości

Nie jest zwracana żadna wartość.

Rejestr zmian

Wersja Opis
5.4.0 Added the optional parameter limit.
5.3.6 Added the optional parameter options.

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  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". If the error has been caused by a PHP internal function then the "message" begins with its name. 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 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. If the optional level is not set, error_reporting() will just return the current error reporting level.

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 or the current level if no level parameter is given.

Rejestr zmian

Wersja Opis
5.4.0 E_STRICT became part of E_ALL.
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 E_RECOVERABLE_ERROR introduced.
5.0.0 E_STRICT introduced (not 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 5.4.

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 ( callable $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 for the error types specified by error_types unless the callback function returns FALSE. 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)
{
    if (!(
error_reporting() & $errno)) {
        
// This error code is not included in error_reporting
        
return;
    }

    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

callable set_exception_handler ( callable $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.

Informacja:

NULL may be passed instead, to reset this handler to its default state.

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. If NULL is passed, resetting the handler to its default state, TRUE is 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 ($divisor == 0) {
    
trigger_error("Cannot divide by zero"E_USER_ERROR);
}
?>

Notatki

Ostrzeżenie

HTML entities in error_msg are not escaped. Use htmlentities() on the message if the error is to be displayed in a browser.

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 Rejestr zmian
inclued.enabled Off PHP_INI_SYSTEM  
inclued.dumpdir NULL 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.

inclued.enabled bool

Whether or not to enable inclued.

inclued.dumpdir string

Location (path) to the directory that stores inclued files. If set, each PHP request will create a file. These files are serialized versions of what inclued_get_data() would produce, so may be unserialized with unserialize().

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 within the PHP application itself (function)

<?php
// File to store the inclued information
$fp fopen('/tmp/wp.ser''w');
if (
$fp) {
    
$clue inclued_get_data();
    if (
$clue) {
        
fwrite($fpserialize($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.ser -o wp.dot

# Next, create the image
$ dot -Tpng -o inclued.png wp.dot

Przykład #3 Listing data via inclued dumps (configuration)

When using the inclued.dumpdir directive, files (include clues) are dumped with every request. Here's one way to list those files, and unserialize() them.

<?php
$path 
ini_get('inclued.dumpdir');
if (
$path && is_dir($path)) {

    echo 
"Path: $path"PHP_EOL;

    
$inclues = new GlobIterator($path DIRECTORY_SEPARATOR 'inclued*');

    if (
$inclues->count() === 0) {
        echo 
'No clues today'PHP_EOL;
        exit;
    }

    foreach (
$inclues as $inclue) {

        echo 
'Inclued file: '$inclue->getFilename(), PHP_EOL;

        
$data file_get_contents($inclue->getPathname());
        if (
$data) {
            
$inc unserialize($data);
            echo 
' -- filename: '$inc['request']['SCRIPT_FILENAME'], PHP_EOL;
            echo 
' -- number of includes: 'count($inc['includes']), PHP_EOL;
        }
        echo 
PHP_EOL;
    }
} else {
    echo 
'I am totally clueless today.'PHP_EOL;
}
?>

Powyższy przykład wyświetli coś podobnego do:

PATH: /tmp/inclued
Inclued file: inclued.56521.1
 -- filename: /Users/philip/test.php
 -- number of includes: 1

Inclued file: inclued.56563.1
 -- filename: /tmp/none.php
 -- number of includes: 0

Inclued file: inclued.56636.1
 -- filename: /tmp/three.php
 -- number of includes: 3




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




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
Nazwa Domyślnie Możliwość zmian
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 usage

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




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 implicit_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
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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


Basic usage

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>
</body>
</html>

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 = true ] )

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.

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 ([ callable $output_callback [, int $chunk_size = 0 [, bool $erase = true ]]] )

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. The default value 0 means that the output function will only be called when the output buffer is closed.

Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes.

erase

If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes. This causes that flushing and cleaning functions would issue a notice and return FALSE if called.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja Opis
5.4.0 A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer.
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




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


Basic usage

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 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 określonej przez nazwa_klasy.

Parametry

nazwa_klasy

Przeciąża nazwę klasy, jako string

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Zobacz przykład w sekcji wprowadzającej tej części podręcznika.


Spis treści

  • overload — Umożliwienie przeciążania właściwości i wołania metod dla klasy



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
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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 Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
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 and PHP 5.2.3.
max_input_vars 1000 PHP_INI_PERDIR Available since PHP 5.3.9.
magic_quotes_gpc "1" PHP_INI_PERDIR PHP_INI_ALL in PHP <= 4.2.3. Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
magic_quotes_runtime "0" PHP_INI_ALL Ta przestarzała funkcja zostanie na pewno w przyszłości usunięta.
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 and GET. It is measured from the moment of receiving all data on the server to the start of script execution.

max_input_nesting_level integer

Sets the max nesting depth of input variables (i.e. $_GET, $_POST..)

max_input_vars integer

How many input variables may be accepted. Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request. This limit applies only to each nesting level of a multi-dimensional input array.

magic_quotes_gpc boolean
Ostrzeżenie

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.

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

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.

If magic_quotes_runtime is enabled, most functions that return data from any sort of external source including databases and text files will have quotes escaped with a backslash. If magic_quotes_sybase is also on, a single-quote is escaped with a single-quote instead of a backslash.

Functions affected by magic_quotes_runtime (does not include functions from PECL):

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.
INI constants
Constant Value Description
INI_USER 1 Unused
INI_PERDIR 2 Unused
INI_SYSTEM 4 Unused
INI_ALL 7 Unused

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

bool 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

This function has been removed from some SAPIs in PHP 5.3.

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\ (PHP 4) or C:\php5\ (PHP 5) 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 or has been disabled (either by setting enable_dl off 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 dl() is now disabled in some SAPIs due to stability issues. The only SAPIs that allow dl() are CLI and Embed. Use the Extension Loading Directives instead.

Notatki

Informacja:

dl() is not supported when PHP is built with ZTS support. Use the Extension Loading Directives instead.

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 )

Forces collection of any existing garbage cycles.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns number of collected cycles.

Zobacz też:



gc_disable

(PHP 5 >= 5.3.0)

gc_disableDeactivates the circular reference collector

Opis

void gc_disable ( void )

Deactivates the circular reference collector, setting zend.enable_gc to 0.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:



gc_enable

(PHP 5 >= 5.3.0)

gc_enableActivates the circular reference collector

Opis

void gc_enable ( void )

Activates the circular reference collector, setting zend.enable_gc to 1.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:



gc_enabled

(PHP 5 >= 5.3.0)

gc_enabledReturns status of the circular reference collector

Opis

bool gc_enabled ( void )

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.

Przykłady

Przykład #1 A gc_enabled() example

<?php
if(gc_enabled()) gc_collect_cycles();
?>

Zobacz też:



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 = false ] )

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
(
    [Core] => 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.3.1 Windows only: Core constants are categorized under Core, previously mhash.
5.3.0 Core constants are categorized under Core, previously internal. On Windows, the Core Constants are categorized under mhash.
5.2.11 The categorize parameter now operates appropriately. Previously, the categorize parameter was interpreted as !is_null($categorize), making any value other than NULL force the constants to be categorized.
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ż:

  • include()
  • include_once()
  • require()
  • require_once()
  • get_required_files() - Alias dla get_included_files



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

Only return Zend extensions, if not then regular extensions, like mysqli are listed. Defaults to FALSE (return regular 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 attempting to set magic_quotes_gpc at runtime will not work.

For more information about magic_quotes, see this security section.

Zwracane wartości

Returns 0 if magic_quotes_gpc is 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 stripslashes($_POST['lastname']);
}
else {
    
$lastname $_POST['lastname'];
}

// If using MySQL
$lastname mysql_real_escape_string($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())
{
    
// Deactivate
    
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(). Many of these variables are listed within » RFC 3875, specifically section 4.1, "Request Meta-Variables".

Parametry

varname

The variable name.

Zwracane wartości

Returns the value of the environment variable varname, or FALSE if the environment variable varname does not exist.

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. Only a-z, A-Z and 0-9 are allowed.
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.

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

Informacja:

The parsing of options will end at the first non-option found, anything that follows is discarded.

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 Parameter longopts is available on all systems.
5.3.0 This function is no longer system dependent, and now 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)
}

Zobacz też:



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 for null values. Returns FALSE if the configuration option doesn't exist.

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.

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 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 information about PHP's configuration

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.

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

The safe_mode_allowed_env_vars and safe_mode_protected_env_vars directives only take effect when safe_mode 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 lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 set_include_path() example

<?php
// Works as of PHP 4.3.0
set_include_path('/usr/lib/pear');

// Works in all PHP versions
ini_set('include_path''/usr/lib/pear');
?>

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. 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') >= 0) {
    echo 
'I am at least PHP version 6.0.0, my version: ' PHP_VERSION "\n";
}

if (
version_compare(PHP_VERSION'5.3.0') >= 0) {
    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




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
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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.





Weak References


Wstęp

Weak references provide a non-intrusive gateway to ephemeral objects. Unlike normal (strong) references, weak references do not prevent the garbage collector from freeing that object. For this reason, an object may be destroyed even though a weak reference to that object still exists. In such conditions, the weak reference seamlessly becomes invalid.

Przykład #1 Weakref usage example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}

unset(
$o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}
?>

Powyższy przykład wyświetli:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!



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/weakref.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




The Weakref class

(No version information available, might only be in SVN)

Wstęp

The Weakref class provides a gateway to objects without preventing the garbage collector from freeing those objects. It also provides a way to turn a weak reference into a strong one.

Krótki opis klasy

Weakref {
/* Metody */
public __construct ([ object $object ] )
public bool acquire ( void )
public object get ( void )
public bool release ( void )
public bool valid ( void )
}

Przykłady

Przykład #1 Weakref usage example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}

unset(
$o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}
?>

Powyższy przykład wyświetli:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!


Weakref::acquire

(No version information available, might only be in SVN)

Weakref::acquireAcquires a strong reference on that object

Opis

public bool Weakref::acquire ( void )

Acquires a strong reference on that object, virtually turning the weak reference into a strong one.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the reference was valid and could be turned into a strong reference, FALSE otherwise.

Przykłady

Przykład #1 Weakref::acquire() example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

$r1->acquire();

echo 
"Unsetting o1...\n";
unset(
$o1);

$o2 $r1->get();

$r1->release();

echo 
"Unsetting o2...\n";
unset(
$o2);
?>

Powyższy przykład wyświetli:

Unsetting o1...
Unsetting o2...
Destroying object!

Przykład #2 Nested acquire/release example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

echo 
"Acquiring...\n";
$r1->acquire();

echo 
"  Unsetting...\n";
unset(
$o1);

echo 
"  Acquiring...\n";
$r1->acquire();

echo 
"    Acquiring...\n";
$r1->acquire();

echo 
"    Releasing...\n";
$r1->release();

echo 
"  Releasing...\n";
$r1->release();

echo 
"Releasing...\n";
$r1->release();

?>

Powyższy przykład wyświetli:

Acquiring...
  Unsetting...
  Acquiring...
    Acquiring...
    Releasing...
  Releasing...
Releasing...
Destroying object!

Zobacz też:



Weakref::__construct

(No version information available, might only be in SVN)

Weakref::__constructConstructs a new weak reference

Opis

public Weakref::__construct() ([ object $object ] )

Constructs a new weak reference.

Parametry

object

The object to reference.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 Weakref::__construct() example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}

unset(
$o1);

if (
$r1->valid()) {
    echo 
"Object still exists!\n";
    
var_dump($r1->get());
} else {
    echo 
"Object is dead!\n";
}
?>

Powyższy przykład wyświetli:

Object still exists!
object(MyClass)#1 (0) {
}
Destroying object!
Object is dead!



Weakref::get

(No version information available, might only be in SVN)

Weakref::getReturns the object pointed to by the weak reference

Opis

public object Weakref::get ( void )

Returns the object pointed to by the weak reference.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the object if the reference is still valid, NULL otherwise.

Zobacz też:



Weakref::release

(No version information available, might only be in SVN)

Weakref::releaseReleases a previously acquired reference

Opis

public bool Weakref::release ( void )

Releases a previously acquired reference. Potentially turning a strong reference back into a weak reference.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the reference was previously acquired and thus could be released, FALSE otherwise.

Przykłady

Przykład #1 Weakref::release() example

<?php
class MyClass {
    public function 
__destruct() {
        echo 
"Destroying object!\n";
    }
}

$o1 = new MyClass;

$r1 = new Weakref($o1);

$r1->acquire();

echo 
"Unsetting o1...\n";
unset(
$o1);

$o2 $r1->get();

$r1->release();

echo 
"Unsetting o2...\n";
unset(
$o2);
?>

Powyższy przykład wyświetli:

Unsetting o1...
Unsetting o2...
Destroying object!

Zobacz też:



Weakref::valid

(No version information available, might only be in SVN)

Weakref::validChecks whether the object referenced still exists

Opis

public bool Weakref::valid ( void )

Checks whether the object referenced still exists.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the object still exists and is thus still accessible via Weakref::get(), FALSE otherwise.

Zobacz też:

  • Weakref::get() - Returns the object pointed to by the weak reference


Spis treści




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

  • Resolve File Path Cache - PHP scripts very often include or operate with files by using relative file paths. Every file path has to be normalized 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 the paths may negatively impact the application's performance. The Windows Cache Extension for PHP provides a Resolve File Path cache, which is used to store the mappings between relative and absolute file paths, thereby reducing the number of path resolutions that the PHP engine has to perform.

  • User Cache (available since version 1.1.0) - PHP scripts can take advantage of the shared memory cache by using the user cache API's. PHP objects and variables can be stored in the user cache and then re-used on subsequent requests. This can be used to improve performance of PHP scripts and to share the data across multiple PHP processes.

  • Session Handler (available since version 1.1.0) - The WinCache session handler can be used to store the PHP session data in the shared memory cache. This avoids file system operations for reading and writing session data, which improves performance when large amount of data is stored in PHP session.



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
Nazwa Domyślnie Minimum Maximum Możliwość zmian Rejestr zmian
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" "255" PHP_INI_SYSTEM Available since WinCache 1.0.0
wincache.fcndetect "1" "0" "1" PHP_INI_SYSTEM Available since WinCache 1.1.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
wincache.ucenabled 1 0 1 PHP_INI_SYSTEM Available since WinCache 1.1.0
wincache.ucachesize 8 5 85 PHP_INI_SYSTEM Available since WinCache 1.1.0
wincache.scachesize 8 5 85 PHP_INI_SYSTEM Available since WinCache 1.1.0
wincache.rerouteini NULL NULL NULL PHP_INI_SYSTEM Available since WinCache 1.2.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.fcndetect boolean
Enables or disables the file change notification detection functionality. If file change notification is supported then it will be used to refresh the opcode and file cache entries as soon as the corresponding files are modified on a file system. If file change notification is not supported, for example when using network file shares, then wincache will poll for file changes at regular time intervals specified by wincache.chkinterval.
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 string
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. The length of the namesalt string cannot exceed 8 characters.
wincache.ucenabled boolean
Enables or disables the user cache functionality.
wincache.ucachesize integer
Defines the maximum memory size in megabytes that is allocated for the user cache. If the total size of variables stored in the user cache exceeds the specified value, then the most stale variables will be removed from the cache.
wincache.scachesize integer
Defines the maximum memory size in megabytes that is allocated for the session cache. If the total size of data stored in the session cache exceeds the specified value, then the most stale data will be removed from the cache.
wincache.rerouteini string
Specifies an absolute or a relateve path to the reroute.ini file that contains the list of PHP functions whose implementation should be replaced with the WinCache function equivalents. If a relative path is specified then it is assumed to be relative to the location of php-cgi.exe file.



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

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



WinCache Session Handler

The WinCache session handler (available since WinCache 1.1.0) can be used to configure PHP to store the session data in shared memory session cache. Using shared memory instead of the default file session storage helps improve performance of PHP applications that store large amount of data in session objects. Wincache session cache uses file-backed shared memory, which ensures that the session data is not lost during recycling of IIS application pools.

To configure PHP to use WinCache session handler set the php.ini setting session.save_handler to wincache. By default the Windows temporary file location is used for storing the session data. To change the location of the session file use session.save_path directive.

Przykład #1 Enabling WinCache session handler

session.save_handler = wincache
session.save_path = C:\inetpub\temp\session\



WinCache Functions Reroutes

The WinCache functions reroutes (available since WinCache 1.2.0) can be used to replace built-in PHP functions with their equivalents that are optimized for a particular purpose. WinCache extension includes Windows-optimized implementation of PHP file functions that may improve performance of PHP applications in cases when PHP has to access files on network shares. The optimized implementation is provided for the following functions:

To configure WinCache to use the functions reroutes use the file reroute.ini that is included in WinCache installation package. Copy this file into the same directory where php.ini file is located. After that add the wincache.rerouteini setting in php.ini and specify an absolute or relative path to the reroute.ini file.

Przykład #1 Enabling WinCache functions reroutes

wincache.rerouteini = C:\PHP\reroute.ini

Informacja: If WinCache functions reroutes are enabled it is recommended to increase the WinCache file cache size. This can be done by using wincache.fcachesize setting.

The reroute.ini file contains the mappings between the native PHP functions and their equivalents in WinCache. Each line in the file defines a mapping by using the following syntax:

<PHP function name>:[<number of function parameters>]=<wincache function name>

The example of the file is shown below. In this example the calls to PHP function file_get_contents() will be replaced with calls to wincache_file_get_contents() only if the number of parameters passed to the function is less than or equals to 2. Specifying the number of parameters is useful when replacement function does not handle all the function's parameters.

Przykład #2 Reroute.ini file content

[FunctionRerouteList]
file_exists=wincache_file_exists
file_get_contents:2=wincache_file_get_contents
readfile:2=wincache_readfile
is_readable=wincache_is_readable
is_writable=wincache_is_writable
is_writeable=wincache_is_writable
is_file=wincache_is_file
is_dir=wincache_is_dir
realpath=wincache_realpath
filesize=wincache_filesize



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 ([ bool $summaryonly = false ] )

Retrieves information about file cache content and its usage.

Parametry

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the file cache summary.

Zwracane wartości

Array of meta data about file cache lub FALSE w przypadku niepowodzenia

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 lub FALSE w przypadku niepowodzenia

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_lock

(PECL wincache >= 1.1.0)

wincache_lock Acquires an exclusive lock on a given key

Opis

bool wincache_lock ( string $key [, bool $isglobal = false ] )

Obtains an exclusive lock on a given key. The execution of the current script will be blocked until the lock can be obtained. Once the lock is obtained, the other scripts that try to request the lock by using the same key will be blocked, until the current script releases the lock by using wincache_unlock().

Ostrzeżenie

Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.

Parametry

key

Name of the key in the cache to get the lock on.

isglobal

Controls whether the scope of the lock is system-wide or local. Local locks are scoped to the application pool in IIS FastCGI case or to all php processes that have the same parent process identifier.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using wincache_lock()

<?php
$fp 
fopen("/tmp/lock.txt""r+");
if (
wincache_lock(“lock_txt_lock”)) { // do an exclusive lock
    
ftruncate($fp0); // truncate file
    
fwrite($fp"Write something here\n");
    
wincache_unlock(“lock_txt_lock”); // release the lock
} else {
    echo 
"Couldn't get the lock!";
}
fclose($fp);
?>

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 ([ bool $summaryonly = false ] )

Retrieves information about opcode cache content and its usage.

Parametry

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the opcode cache summary.

Zwracane wartości

Array of meta data about opcode cache lub FALSE w przypadku niepowodzenia

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
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global 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 lub FALSE w przypadku niepowodzenia

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 resolve file path cache

Opis

array wincache_rplist_fileinfo ([ bool $summaryonly = false ] )

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

Zwracane wartości

Array of meta data about the resolve file path cache lub FALSE w przypadku niepowodzenia

The array returned by this function contains the following elements:

  • total_file_count - total number of file path mappings stored in the cache
  • rplist_entries - an array that contains the information about all the cached file paths:

    • resolve_path - 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
                (
                    [resolve_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 resolve file path cache

Opis

array wincache_rplist_meminfo ( void )

Retrieves information about memory usage by resolve file path cache.

Zwracane wartości

Array of meta data that describes memory usage by resolve file path cache. lub FALSE w przypadku niepowodzenia

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the resolve file path cache
  • memory_free - amount of free memory in bytes available for the resolve file path cache
  • num_used_blks - number of memory blocks used by the resolve file path cache
  • num_free_blks - number of free memory blocks available for the resolve file path cache
  • memory_overhead - amount of memory in bytes used for the internal structures of resolve 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ż:



wincache_scache_info

(PECL wincache >= 1.1.0)

wincache_scache_info Retrieves information about files cached in the session cache

Opis

array wincache_scache_info ([ bool $summaryonly = false ] )

Retrieves information about session cache content and its usage.

Parametry

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the session cache summary.

Zwracane wartości

Array of meta data about session cache lub FALSE w przypadku niepowodzenia

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the session cache has been active
  • total_item_count - total number of elements that are currently in the session cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
  • total_hit_count - number of times the data has been served from the cache
  • total_miss_count - number of times the data has not been found in the cache
  • scache_entries - an array that contains the information about all the cached items:

    • key_name - name of the key which is used to store the data
    • value_type - type of value stored by the key
    • 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
    • ttl_seconds - time remaining for the data to live in the cache, 0 meaning infinite
    • age_seconds - time elapsed from the time data has been added in the cache
    • hitcount - number of times data has been served from the cache

Przykłady

Przykład #1 A wincache_scache_info() example

<pre>
<?php
print_r
(wincache_scache_info());
?>
</pre>

Powyższy przykład wyświetli:

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [scache_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_scache_meminfo

(PECL wincache >= 1.1.0)

wincache_scache_meminfo Retrieves information about session cache memory usage

Opis

array wincache_scache_meminfo ( void )

Retrieves information about memory usage by session cache.

Zwracane wartości

Array of meta data about session cache memory usage lub FALSE w przypadku niepowodzenia

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the session cache
  • memory_free - amount of free memory in bytes available for the session cache
  • num_used_blks - number of memory blocks used by the session cache
  • num_free_blks - number of free memory blocks available for the session cache
  • memory_overhead - amount of memory in bytes used for the session cache internal structures

Przykłady

Przykład #1 A wincache_scache_meminfo() example

<pre>
<?php
print_r
(wincache_scache_meminfo());
?>
</pre>

Powyższy przykład wyświetli:

Array 
( 
    [memory_total] => 5242880 
    [memory_free] => 5215056 
    [num_used_blks] => 6 
    [num_free_blks] => 3 
    [memory_overhead] => 176
) 

Zobacz też:



wincache_ucache_add

(PECL wincache >= 1.1.0)

wincache_ucache_add Adds a variable in user cache only if variable does not already exist in the cache

Opis

bool wincache_ucache_add ( string $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_add ( array $values [, mixed $unused [, int $ttl = 0 ]] )

Adds a variable in user cache, only if this variable doesn't already exist in the cache. The added variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Parametry

key

Store the variable using this key name. If a variable with same key is already present the function will fail and return FALSE. key is case sensitive. To override the value even if key is present use wincache_ucache_set() function instad. key can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition.

value

Value of a variable to store. Value supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass NULL as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

values

Associative array of keys and values.

ttl

Time for the variable to live in the cache in seconds. After the value specified in ttl has passed the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Zwracane wartości

If key is string, the function returns TRUE on success and FALSE on failure.

If key is an array, the function returns:

  • If all the name => value pairs in the array can be set, function returns an empty array;
  • If all the name => value pairs in the array cannot be set, function returns FALSE;
  • If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

Przykłady

Przykład #1 wincache_ucache_add() with key as a string

<?php
$bar 
'BAR';
var_dump(wincache_ucache_add('foo'$bar));
var_dump(wincache_ucache_add('foo'$bar));
var_dump(wincache_ucache_get('foo'));
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)
string(3) "BAR" 

Przykład #2 wincache_ucache_add() with key as an array

<?php
$colors_array 
= array('green' => '5''Blue' => '6''yellow' => '7''cyan' => '8');
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>

Powyższy przykład wyświetli:

array(0) { } 
array(4) { 
  ["green"]=> int(-1) 
  ["Blue"]=> int(-1) 
  ["yellow"]=> int(-1) 
  ["cyan"]=> int(-1) 
} 
string(1) "6"

Zobacz też:



wincache_ucache_cas

(PECL wincache >= 1.1.0)

wincache_ucache_cas Compares the variable with old value and assigns new value to it

Opis

bool wincache_ucache_cas ( string $key , int $old_value , int $new_value )

Compares the variable associated with the key with old_value and if it matches then assigns the new_value to it.

Parametry

key

The key that is used to store the variable in the cache. key is case sensitive.

old_value

Old value of the variable pointed by key in the user cache. The value should be of type long, otherwise the function returns FALSE.

new_value

New value which will get assigned to variable pointer by key if a match is found. The value should be of type long, otherwise the function returns FALSE.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using wincache_ucache_cas()

<?php
wincache_ucache_set
('counter'2922);
var_dump(wincache_ucache_cas('counter'29221));
var_dump(wincache_ucache_get('counter'));
?>

Powyższy przykład wyświetli:

bool(true) 
int(1)

Zobacz też:



wincache_ucache_clear

(PECL wincache >= 1.1.0)

wincache_ucache_clear Deletes entire content of the user cache

Opis

bool wincache_ucache_clear ( void )

Clears/deletes all the values stored in the user cache.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 using wincache_ucache_clear()

<?php
wincache_ucache_set
('green'1);
wincache_ucache_set('red'2);
wincache_ucache_set('orange'4);
wincache_ucache_set('blue'8);
wincache_ucache_set('cyan'16);
$array1 = array('green''red''orange''blue''cyan');
var_dump(wincache_ucache_get($array1));
var_dump(wincache_ucache_clear());
var_dump(wincache_ucache_get($array1));
?>

Powyższy przykład wyświetli:

array(5) { ["green"]=> int(1) 
           ["red"]=> int(2) 
           ["orange"]=> int(4) 
           ["blue"]=> int(8) 
           ["cyan"]=> int(16) } 
bool(true) 
bool(false) 

Zobacz też:



wincache_ucache_dec

(PECL wincache >= 1.1.0)

wincache_ucache_dec Decrements the value associated with the key

Opis

mixed wincache_ucache_dec ( string $key [, int $dec_by = 1 [, bool &$success ]] )

Decrements the value associated with the key by 1 or as specified by dec_by.

Parametry

key

The key that was used to store the variable in the cache. key is case sensitive.

dec_by

The value by which the variable associated with the key will get decremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the key should be of type long, otherwise the function fails and returns FALSE.

success

Will be set to TRUE on success and FALSE on failure.

Zwracane wartości

Returns the decremented value on success and FALSE on failure.

Przykłady

Przykład #1 Using wincache_ucache_dec()

<?php
wincache_ucache_set
('counter'1);
var_dump(wincache_ucache_dec('counter'2923$success));
var_dump($success);
?>

Powyższy przykład wyświetli:

int(2922) 
bool(true)

Zobacz też:



wincache_ucache_delete

(PECL wincache >= 1.1.0)

wincache_ucache_delete Deletes variables from the user cache

Opis

bool wincache_ucache_delete ( mixed $key )

Deletes the elements in the user cache pointed by key.

Parametry

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

If key is an array then the function returns FALSE if every element of the array fails to get deleted from the user cache, otherwise returns an array which consists of all the keys that are deleted.

Przykłady

Przykład #1 Using wincache_ucache_delete() with key as a string

<?php
wincache_ucache_set
('foo''bar');
var_dump(wincache_ucache_delete('foo'));
var_dump(wincache_ucache_exists('foo'));
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

Przykład #2 Usingwincache_ucache_delete() with key as an array

<?php
$array1 
= array('green' => '5''blue' => '6''yellow' => '7''cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green''blue''yellow''cyan');
var_dump(wincache_ucache_delete($array2));
?>

Powyższy przykład wyświetli:

array(4) { [0]=> string(5) "green" 
           [1]=> string(4) "Blue" 
           [2]=> string(6) "yellow" 
           [3]=> string(4) "cyan" } 

Przykład #3 Using wincache_ucache_delete() with key as an array where some elements cannot be deleted

<?php
$array1 
= array('green' => '5''blue' => '6''yellow' => '7''cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('orange''red''yellow''cyan');
var_dump(wincache_ucache_delete($array2));
?>

Powyższy przykład wyświetli:

array(2) { [0]=> string(6) "yellow" 
           [1]=> string(4) "cyan" }

Zobacz też:



wincache_ucache_exists

(PECL wincache >= 1.1.0)

wincache_ucache_exists Checks if a variable exists in the user cache

Opis

bool wincache_ucache_exists ( string $key )

Checks if a variable with the key exists in the user cache or not.

Parametry

key

The key that was used to store the variable in the cache. key is case sensitive.

Zwracane wartości

Returns TRUE if variable with the key exitsts, otherwise returns FALSE.

Przykłady

Przykład #1 Using wincache_ucache_exists()

<?php
if (!wincache_ucache_exists('green'))
    
wincache_ucache_set('green'1);
var_dump(wincache_ucache_exists('green'));
?>

Powyższy przykład wyświetli:

bool(true)

Zobacz też:



wincache_ucache_get

(PECL wincache >= 1.1.0)

wincache_ucache_get Gets a variable stored in the user cache

Opis

mixed wincache_ucache_get ( mixed $key [, bool &$success ] )

Gets a variable stored in the user cache.

Parametry

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys. In this case the return value will be an array of values of each element in the key array. If an object, or an array containing objects, is returned, then the objects will be unserialized. See __wakeup() for details on unserializing objects.

success

Will be set to TRUE on success and FALSE on failure.

Zwracane wartości

If key is a string, the function returns the value of the variable stored with that key. The success is set to TRUE on success and to FALSE on failure.

The key is an array, the parameter success is always set to TRUE. The returned array (name => value pairs) will contain only those name => value pairs for which the get operation in user cache was successful. If none of the keys in the key array finds a match in the user cache an empty array will be returned.

Przykłady

Przykład #1 wincache_ucache_get() with key as a string

<?php
wincache_ucache_add
('color''blue');
var_dump(wincache_ucache_get('color'$success));
var_dump($success);
?>

Powyższy przykład wyświetli:

string(4) "blue"
bool(true)

Przykład #2 wincache_ucache_get() with key as an array

<?php
$array1 
= array('green' => '5''Blue' => '6''yellow' => '7''cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green''Blue''yellow''cyan');
var_dump(wincache_ucache_get($array2$success));
var_dump($success);
?>

Powyższy przykład wyświetli:

array(4) { ["green"]=> string(1) "5" 
           ["Blue"]=> string(1) "6" 
           ["yellow"]=> string(1) "7" 
           ["cyan"]=> string(1) "8" } 
bool(true) 

Zobacz też:



wincache_ucache_inc

(PECL wincache >= 1.1.0)

wincache_ucache_inc Increments the value associated with the key

Opis

mixed wincache_ucache_inc ( string $key [, int $inc_by = 1 [, bool &$success ]] )

Increments the value associated with the key by 1 or as specified by inc_by.

Parametry

key

The key that was used to store the variable in the cache. key is case sensitive.

inc_by

The value by which the variable associated with the key will get incremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the key should be of type long, otherwise the function fails and returns FALSE.

success

Will be set to TRUE on success and FALSE on failure.

Zwracane wartości

Returns the incremented value on success and FALSE on failure.

Przykłady

Przykład #1 Using wincache_ucache_inc()

<?php
wincache_ucache_set
('counter'1);
var_dump(wincache_ucache_inc('counter'2921$success));
var_dump($success);
?>

Powyższy przykład wyświetli:

int(2922) 
bool(true)

Zobacz też:



wincache_ucache_info

(PECL wincache >= 1.1.0)

wincache_ucache_info Retrieves information about data stored in the user cache

Opis

array wincache_ucache_info ([ bool $summaryonly = false [, string $key ]] )

Retrieves information about data stored in the user cache.

Parametry

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the user cache summary.

key

The key of an entry in the user cache. If specified then the returned array will contain information only about that cache entry. If not specified and summaryonly is set to FALSE then the returned array will contain information about all entries in the cache.

Zwracane wartości

Array of meta data about user cache lub FALSE w przypadku niepowodzenia

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the user cache has been active
  • total_item_count - total number of elements that are currently in the user cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
  • total_hit_count - number of times the data has been served from the cache
  • total_miss_count - number of times the data has not been found in the cache
  • ucache_entries - an array that contains the information about all the cached items:

    • key_name - name of the key which is used to store the data
    • value_type - type of value stored by the key
    • 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
    • is_session - indicates if the data is a session variable
    • ttl_seconds - time remaining for the data to live in the cache, 0 meaning infinite
    • age_seconds - time elapsed from the time data has been added in the cache
    • hitcount - number of times data has been served from the cache

Przykłady

Przykład #1 Using wincache_ucache_info()

<?php
wincache_ucache_get
('green');
wincache_ucache_set('green'2922);
wincache_ucache_get('green');
wincache_ucache_get('green');
wincache_ucache_get('green');
print_r(wincache_ucache_info());
?>

Powyższy przykład wyświetli:

Array 
( ["total_cache_uptime"] => int(0)
  ["is_local_cache"] => bool(false)
  ["total_item_count"] => int(1) 
  ["total_hit_count"] => int(3) 
  ["total_miss_count"] => int(1) 
  ["ucache_entries"] => Array(1) 
    ( [1] => Array(6)
      ( 
        ["key_name"] => string(5) "green"
        ["value_type"] => string(4) "long" 
        ["is_session"] => int(0) 
        ["ttl_seconds"] => int(0)
        ["age_seconds"] => int(0)
        ["hitcount"] => int(3) 
       ) 
    ) 
)

Zobacz też:



wincache_ucache_meminfo

(PECL wincache >= 1.1.0)

wincache_ucache_meminfo Retrieves information about user cache memory usage

Opis

array wincache_ucache_meminfo ( void )

Retrieves information about memory usage by user cache.

Zwracane wartości

Array of meta data about user cache memory usage lub FALSE w przypadku niepowodzenia

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the user cache
  • memory_free - amount of free memory in bytes available for the user cache
  • num_used_blks - number of memory blocks used by the user cache
  • num_free_blks - number of free memory blocks available for the user cache
  • memory_overhead - amount of memory in bytes used for the user cache internal structures

Przykłady

Przykład #1 A wincache_ucache_meminfo() example

<pre>
<?php
print_r
(wincache_ucache_meminfo());
?>
</pre>

Powyższy przykład wyświetli:

Array 
( 
    [memory_total] => 5242880 
    [memory_free] => 5215056 
    [num_used_blks] => 6 
    [num_free_blks] => 3 
    [memory_overhead] => 176
) 

Zobacz też:



wincache_ucache_set

(PECL wincache >= 1.1.0)

wincache_ucache_set Adds a variable in user cache and overwrites a variable if it already exists in the cache

Opis

bool wincache_ucache_set ( mixed $key , mixed $value [, int $ttl = 0 ] )
bool wincache_ucache_set ( array $values [, mixed $unused [, int $ttl = 0 ]] )

Adds a variable in user cache. Overwrites a variable if it already exists in the cache. The added or updated variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Parametry

key

Store the variable using this key name. If a variable with same key is already present the function will overwrite the previous value with the new one. key is case sensitive. key can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition.

value

Value of a variable to store. Value supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass NULL as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

values

Associative array of keys and values.

ttl

Time for the variable to live in the cache in seconds. After the value specified in ttl has passed the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

Zwracane wartości

If key is string, the function returns TRUE on success and FALSE on failure.

If key is an array, the function returns:

  • If all the name => value pairs in the array can be set, function returns an empty array;
  • If all the name => value pairs in the array cannot be set, function returns FALSE;
  • If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

Przykłady

Przykład #1 wincache_ucache_set() with key as a string

<?php
$bar 
'BAR';
var_dump(wincache_ucache_set('foo'$bar));
var_dump(wincache_ucache_get('foo'));
$bar1 'BAR1';
var_dump(wincache_ucache_set('foo'$bar1));
var_dump(wincache_ucache_get('foo'));
?>

Powyższy przykład wyświetli:

bool(true)
string(3) "BAR"
bool(true)
string(3) "BAR1"

Przykład #2 wincache_ucache_set() with key as an array

<?php
$colors_array 
= array('green' => '5''Blue' => '6''yellow' => '7''cyan' => '8');
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>

Powyższy przykład wyświetli:

array(0) {}
array(0) {}
string(1) "6"

Zobacz też:



wincache_unlock

(PECL wincache >= 1.1.0)

wincache_unlock Releases an exclusive lock on a given key

Opis

bool wincache_unlock ( string $key )

Releases an exclusive lock that was obtained on a given key by using wincache_lock(). If any other process was blocked waiting for the lock on this key, that process will be able to obtain the lock.

Ostrzeżenie

Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.

Parametry

key

Name of the key in the cache to release the lock on.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Using wincache_unlock()

<?php
$fp 
fopen("/tmp/lock.txt""r+");
if (
wincache_lock(“lock_txt_lock”)) { // do an exclusive lock
    
ftruncate($fp0); // truncate file
    
fwrite($fp"Write something here\n");
    
wincache_unlock(“lock_txt_lock”); // release the lock
} else {
    echo 
"Couldn't get the lock!";
}
fclose($fp);
?>

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.





Hierarchical Profiler


Wstęp

XHProf is a light-weight hierarchical and instrumentation based profiler. During the data collection phase, it keeps track of call counts and inclusive metrics for arcs in the dynamic callgraph of a program. It computes exclusive metrics in the reporting/post processing phase, such as wall (elapsed) time, CPU time and memory usage. A functions profile can be broken down by callers or callees. XHProf handles recursive functions by detecting cycles in the callgraph at data collection time itself and avoiding the cycles by giving unique depth qualified names for the recursive invocations.

XHProf includes a simple HTML based user interface (written in PHP). The browser based UI for viewing profiler results makes it easy to view results or to share results with peers. A callgraph image view is also supported.

XHProf reports can often be helpful in understanding the structure of the code being executed. The hierarchical nature of the reports can be used to determine, for example, what chain of calls led to a particular function getting called.

XHProf supports ability to compare two runs (a.k.a. "diff" reports) or aggregate data from multiple runs. Diff and aggregate reports, much like single run reports, offer "flat" as well as "hierarchical" views of the profile.

Additional documentation can be found via the » facebook xhprof website.



Instalacja/Konfiguracja

Spis treści


Wymagania

Although not required, xhprof includes an interface that's written in PHP. It's used to save and display the profiled data in a usable way, where viewing is done via a web browser. So, a PHP enabled web server will likely make the xhprof experience more useful.

There's also a fork of the GUI interface at » http://github.com/preinheimer/xhprof



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/xhprof



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Xhprof Opcje konfiguracyjne
Nazwa Domyślnie Możliwość zmian Rejestr zmian
xhprof.output_dir "" PHP_INI_ALL  

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

xhprof.output_dir string

Directory used by the default implementation of the iXHProfRuns interface (namely, the XHProfRuns_Default class) for storing XHProf runs.



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.

XHPROF_FLAGS_NO_BUILTINS (integer)
Used to skip all built-in (internal) functions.
XHPROF_FLAGS_CPU (integer)
Used to add CPU profiling information to the output.
XHPROF_FLAGS_MEMORY (integer)
Used to add memory profiling information to the output.


Przykłady

Przykład #1 Xhprof example with the optional GUI

This example starts and stops the profiler, then uses the bundled GUI interface to save and parse the results. In other words, the code from the extension itself ends at the call to xhprof_disable().

<?php
xhprof_enable
(XHPROF_FLAGS_CPU XHPROF_FLAGS_MEMORY);

for (
$i 0$i <= 1000$i++) {
    
$a $i $i;
}

$xhprof_data xhprof_disable();

$XHPROF_ROOT "/tools/xhprof/";
include_once 
$XHPROF_ROOT "/xhprof_lib/utils/xhprof_lib.php";
include_once 
$XHPROF_ROOT "/xhprof_lib/utils/xhprof_runs.php";

$xhprof_runs = new XHProfRuns_Default();
$run_id $xhprof_runs->save_run($xhprof_data"xhprof_testing");

echo 
"http://localhost/xhprof/xhprof_html/index.php?run={$run_id}&source=xhprof_testing\n";

?>

Powyższy przykład wyświetli coś podobnego do:

http://localhost/xhprof/xhprof_html/index.php?run=t11_4bdf44d21121f&source=xhprof_testing


Xhprof Funkcje


xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disableStops xhprof profiler

Opis

array xhprof_disable ( void )

Stops the profiler, and returns xhprof data from the run.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of xhprof data, from the run.

Przykłady

Przykład #1 xhprof_disable() example

<?php
xhprof_enable
();

$foo strlen("foo bar");

$xhprof_data xhprof_disable();

print_r($xhprof_data);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [main()==>strlen] => Array
        (
            [ct] => 1
            [wt] => 279
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 9
        )

    [main()] => Array
        (
            [ct] => 1
            [wt] => 610
        )

)


xhprof_enable

(PECL xhprof >= 0.9.0)

xhprof_enableStart xhprof profiler

Opis

void xhprof_enable ([ int $flags = 0 [, array $options ]] )

Start xhprof profiling.

Parametry

flags

Optional flags to add additional information to the profiling. See the XHprof constants for further information about these flags, e.g., XHPROF_FLAGS_MEMORY to enable memory profiling.

options

An array of optional options, namely, the 'ignored_functions' option to pass in functions to be ignored during profiling.

Zwracane wartości

NULL

Rejestr zmian

Wersja Opis
0.9.2 The optional options parameter was added.

Przykłady

Przykład #1 xhprof_enable() examples

<?php
// 1. elapsed time + memory + CPU profiling; and ignore built-in (internal) functions
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS XHPROF_FLAGS_CPU XHPROF_FLAGS_MEMORY);

// 2. elapsed time profiling; ignore call_user_func* during profiling
xhprof_enable(
    
0,
    array(
'ignored_functions' =>  array('call_user_func',
                                        
'call_user_func_array')));
                                       
// 3. elapsed time + memory profiling; ignore call_user_func* during profiling
xhprof_enable(
    
XHPROF_FLAGS_MEMORY,
    array(
'ignored_functions' =>  array('call_user_func',
                                        
'call_user_func_array')));
?>

Zobacz też:



xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disableStops xhprof sample profiler

Opis

array xhprof_sample_disable ( void )

Stops the sample mode xhprof profiler, and

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

An array of xhprof sample data, from the run.

Przykłady

Przykład #1 xhprof_sample_disable() example

<?php
xhprof_sample_enable
();

for (
$i 0$i <= 10000$i++) {
    
$a strlen($i);
    
$b $i $a;
    
$c rand();
}

$xhprof_data xhprof_sample_disable();

print_r($xhprof_data);
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [1272935300.800000] => main()
    [1272935300.900000] => main()
)


xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enableDescription

Opis

void xhprof_sample_enable ( void )

Starts profiling in sample mode, which is a lighter weight version of xhprof_enable(). The sampling interval is 0.1 seconds, and samples record the full function call stack. The main use case is when lower overhead is required when doing performance monitoring and diagnostics.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

NULL

Zobacz też:


Spis treści





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

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/id3.

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

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

Genre name as string.

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_set_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

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/ktaglib.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/




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
Picture type BandLogo


The KTaglib_MPEG_File class

(No version information available, might only be in SVN)

Wstęp

Represents an MPEG file. MPEG files can have ID3v1, ID3v2 tags and audio properties.

Class synopsis

KTaglib_MPEG_File {
/* Metody */
public KTaglib_MPEG_File getAudioProperties ( void )
public KTaglib_ID3v1_Tag getID3v1Tag ([ bool $create = false ] )
public KTaglib_ID3v2_Tag getID3v2Tag ([ bool $create = false ] )
}

KTaglib_MPEG_File::__construct

(0.0.1)

KTaglib_MPEG_File::__constructOpens a new file

Opis

public 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

(No version information available, might only be in SVN)

Wstęp

Represents the audio properties of a MPEG file, like length, bitrate or samplerate.


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 if the file is marked as the original 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

(No version information available, might only be in SVN)

Wstęp

Base class for ID3v1 or ID3v2 tags

Class synopsis

KTaglib_Tag {
/* Metody */
public string getAlbum ( void )
public string getArtist ( void )
public string getComment ( void )
public string getGenre ( void )
public string getTitle ( void )
public int getTrack ( void )
public int getYear ( void )
public bool isEmpty ( void )
}

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

(No version information available, might only be in SVN)

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

extends KTaglib_Tag {
/* Metody */
public bool addFrame ( KTaglib_ID3v2_Frame $frame )
public array getFrameList ( void )
/* Metody dziedziczone */
public string KTaglib_Tag::getAlbum ( void )
public string KTaglib_Tag::getArtist ( void )
public string KTaglib_Tag::getComment ( void )
public string KTaglib_Tag::getGenre ( void )
public string KTaglib_Tag::getTitle ( void )
public int KTaglib_Tag::getTrack ( void )
public int KTaglib_Tag::getYear ( void )
public bool KTaglib_Tag::isEmpty ( void )
}

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

(No version information available, might only be in SVN)

Wstęp

The base class for ID3v2 frames. ID3v2 tags are separated in various specialized frames. Some frames can exists multiple times.

Class synopsis

extends KTaglib_Tag {
/* Metody */
public int getSize ( void )
public string __toString ( void )
/* Metody dziedziczone */
public string KTaglib_Tag::getAlbum ( void )
public string KTaglib_Tag::getArtist ( void )
public string KTaglib_Tag::getComment ( void )
public string KTaglib_Tag::getGenre ( void )
public string KTaglib_Tag::getTitle ( void )
public int KTaglib_Tag::getTrack ( void )
public int KTaglib_Tag::getYear ( void )
public bool KTaglib_Tag::isEmpty ( void )
}

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

(No version information available, might only be in SVN)

Wstęp

Represents an ID3v2 frame that can hold a picture.

Class synopsis

/* Metody */
public string getDescription ( void )
public string getMimeType ( void )
public int getType ( void )
public bool savePicture ( string $filename )
public string getMimeType ( string $type )
public void setPicture ( string $filename )
public void setType ( int $type )
/* Metody dziedziczone */
public int KTaglib_ID3v2_Frame::getSize ( void )
public string KTaglib_ID3v2_Frame::__toString ( void )
public string KTaglib_Tag::getAlbum ( void )
public string KTaglib_Tag::getArtist ( void )
public string KTaglib_Tag::getComment ( void )
public string KTaglib_Tag::getGenre ( void )
public string KTaglib_Tag::getTitle ( void )
public int KTaglib_Tag::getTrack ( void )
public int KTaglib_Tag::getYear ( void )
public bool KTaglib_Tag::isEmpty ( void )
}

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 lub FALSE w przypadku niepowodzenia.

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) lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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

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/kadm5.

Informacja:

If this option is used 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.

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


Basic usage

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 lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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

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/radius.

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

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 (int)
IPv4 Internet network 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
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
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





Rozszerzenia daty i czasu


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
5.0.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 calendars 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.

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.

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.

Informacje o dacie i czasie są wewnętrzenie przechowywane jako liczby 64 bitowe, dlatego obsługiwane są wszystkie dające się wyobrazić daty (włącznie z latami ujemnymi). Zakres dat jest od 292 miliardów lat w przeszłości do 292 miliardów lat w przyszłości.

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.

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
Nazwa Domyślnie Możliwość zmian Rejestr zmian
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. Prior to PHP 5.4.0, this would only work if the TZ environment variable was not set. The precedence order for which timezone is used if none is explicitly mentioned 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)


The DateTime class

(PHP 5 >= 5.2.0)

Wstęp

Representation of date and time.

Krótki opis klasy

DateTime {
/* Stałe */
const string ATOM = "Y-m-d\TH:i:sP" ;
const string COOKIE = "l, d-M-y H:i:s T" ;
const string ISO8601 = "Y-m-d\TH:i:sO" ;
const string RFC822 = "D, d M y H:i:s O" ;
const string RFC850 = "l, d-M-y H:i:s T" ;
const string RFC1036 = "D, d M y H:i:s O" ;
const string RFC1123 = "D, d M Y H:i:s O" ;
const string RFC2822 = "D, d M Y H:i:s O" ;
const string RFC3339 = "Y-m-d\TH:i:sP" ;
const string RSS = "D, d M Y H:i:s O" ;
const string W3C = "Y-m-d\TH:i:sP" ;
/* Metody */
public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
public DateTime add ( DateInterval $interval )
public static DateTime createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
public DateInterval diff ( DateTime $datetime2 [, bool $absolute = false ] )
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 = 1 ] )
public DateTime setTime ( int $hour , int $minute [, int $second = 0 ] )
public DateTime setTimestamp ( int $unixtimestamp )
public DateTime setTimezone ( DateTimeZone $timezone )
public DateTime sub ( DateInterval $interval )
public DateTime __wakeup ( void )
}

Stałe predefiniowane

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)

Rejestr zmian

Wersja Opis
5.2.2 DateTime object comparison with the comparison operators changed to work as expected. Previously, all DateTime objects were considered equal (using ==).


DateTime::add

date_add

(PHP 5 >= 5.3.0)

DateTime::add -- date_add Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object

Opis

Styl obiektowy

public DateTime DateTime::add ( DateInterval $interval )

Styl proceduralny

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(). Funkcja modyfikuje ten obiekt.

interval

A DateInterval object

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::add() example

Styl obiektowy

<?php
$date 
= new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo 
$date->format('Y-m-d') . "\n";
?>

Styl proceduralny

<?php
$date 
date_create('2000-01-01');
date_add($datedate_interval_create_from_date_string('10 days'));
echo 
date_format($date'Y-m-d');
?>

Powyższe przykłady wyświetlą:

2000-01-11

Przykład #2 Further DateTime::add() examples

<?php
$date 
= new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

Powyższy przykład wyświetli:

2000-01-01 10:00:30
2007-06-05 04:03:02

Przykład #3 Beware when adding months

<?php
$date 
= new DateTime('2000-12-31');
$interval = new DateInterval('P1M');

$date->add($interval);
echo 
$date->format('Y-m-d') . "\n";

$date->add($interval);
echo 
$date->format('Y-m-d') . "\n";
?>

Powyższy przykład wyświetli:

2001-01-31
2001-03-03

Notatki

DateTime::modify() is an alternative when using PHP 5.2.

Zobacz też:



DateTime::__construct

date_create

(PHP 5 >= 5.2.0)

DateTime::__construct -- date_createReturns new DateTime object

Opis

Styl obiektowy

public DateTime::__construct() ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Styl proceduralny

DateTime date_create ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )

Returns new DateTime object.

Parametry

time

Łańcuch daty/czasu. Prawidłowe formaty są wyjaśnione pod adresem Formaty daty i czasu.

Enter NULL here to obtain the current time when using the $timezone parameter.

timezone

A DateTimeZone object representing the desired time zone.

If $timezone is omitted, the current timezone will be used.

Informacja:

The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Zwracane wartości

Returns a new DateTime instance. Styl proceduralny zwraca FALSE w przypadku niepowodzenia.

Błędy/Wyjątki

Emits Exception in case of an error.

Rejestr zmian

Wersja Opis
5.3.0 If an invalid date is specified, then an exception is now thrown. Previously an error was emitted.

Przykłady

Przykład #1 DateTime::__construct() example

Styl obiektowy

<?php
try {
    
$date = new DateTime('2000-01-01');
} catch (
Exception $e) {
    echo 
$e->getMessage();
    exit(
1);
}

echo 
$date->format('Y-m-d');
?>

Styl proceduralny

<?php
$date 
date_create('2000-01-01');
if (!
$date) {
    
$e date_get_last_errors();
    foreach (
$e['errors'] as $error) {
        echo 
"$error\n";
    }
    exit(
1);
}

echo 
date_format($date'Y-m-d');
?>

Powyższe przykłady wyświetlą:

2000-01-01

Przykład #2 Intricacies of DateTime::__construct()

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo 
$date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo 
$date->format('Y-m-d H:i:sP') . "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00

Zobacz też:



DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0)

DateTime::createFromFormat -- date_create_from_formatReturns new DateTime object formatted according to the specified format

Opis

Styl obiektowy

public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )

Styl proceduralny

DateTime date_create_from_format ( string $format , string $time [, DateTimeZone $timezone ] )

Returns new DateTime object formatted according to the specified format.

Parametry

format

The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

The following characters are recognized in the format parameter string
format character Description Example parsable values
Day --- ---
d and j Day of the month, 2 digits with or without leading zeros 01 to 31 or 1 to 31
D and l A textual representation of a day Mon through Sun or Sunday through Saturday
S English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. st, nd, rd or th.
z The day of the year (starting from 0) 0 through 365
Month --- ---
F and M A textual representation of a month, such as January or Sept January through December or Jan through Dec
m and n Numeric representation of a month, with or without leading zeros 01 through 12 or 1 through 12
Year --- ---
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a and A Ante meridiem and Post meridiem am or pm
g and h 12-hour format of an hour with or without leading zero 1 through 12 or 01 through 12
G and H 24-hour format of an hour with or without leading zeros 0 through 23 or 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
u Microseconds (up to six digits) Example: 45, 654321
Timezone --- ---
e, O, P and T Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation Examples: UTC, GMT, Atlantic/Azores or +0200 or +02:00 or EST, MDT
Full Date/Time --- ---
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Example: 1292177455
Whitespace and Separators --- ---
(space) One space or one tab Example:
# One of the following separation symbol: ;, :, /, ., ,, -, ( or ) Example: /
;, :, /, ., ,, -, ( or ) The specified character. Example: -
? A random byte Example: ^ (Be aware that for UTF-8 characracters you might need more than one ?. In this case, using * is probably what you want instead)
* Random bytes until the next separator or digit Example: * in Y-*-d with the string 2009-aWord-08 will match aWord
! Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch Without !, all fields will be set to the current date and time.
| Resets all fields (year, month, day, hour, minute, second, fraction and timzone information) to the Unix Epoch if they have not been parsed yet Y-m-d| will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0.
+ If this format specifier is present, trailing data in the string will not cause an error, but a warning instead Use DateTime::getLastErrors() to find out whether trailing data was present.

Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTime::getLastErrors().

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC.

time

String representing the time.

timezone

A DateTimeZone object representing the desired time zone.

If timezone is omitted and time contains no timezone, the current timezone will be used.

Informacja:

The timezone parameter and the current timezone are ignored when the time parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Zwracane wartości

Returns a new DateTime instance lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::createFromFormat() example

Styl obiektowy

<?php
$date 
DateTime::createFromFormat('j-M-Y''15-Feb-2009');
echo 
$date->format('Y-m-d');
?>

Styl proceduralny

<?php
$date 
date_create_from_format('j-M-Y''15-Feb-2009');
echo 
date_format($date'Y-m-d');
?>

Powyższe przykłady wyświetlą:

2009-02-15

Przykład #2 Intricacies of DateTime::createFromFormat()

<?php
echo 'Current time: ' date('Y-m-d H:i:s') . "\n";

$format 'Y-m-d';
$date DateTime::createFromFormat($format'2009-02-15');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format 'Y-m-d H:i:s';
$date DateTime::createFromFormat($format'2009-02-15 15:16:17');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format 'Y-m-!d H:i:s';
$date DateTime::createFromFormat($format'2009-02-15 15:16:17');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";

$format '!d';
$date DateTime::createFromFormat($format'15');
echo 
"Format: $format; " $date->format('Y-m-d H:i:s') . "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

Current time: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00

Zobacz też:



DateTime::diff

date_diff

(PHP 5 >= 5.3.0)

DateTime::diff -- date_diffReturns the difference between two DateTime objects

Opis

Styl obiektowy

public DateInterval DateTime::diff ( DateTime $datetime2 [, bool $absolute = false ] )

Styl proceduralny

DateInterval date_diff ( DateTime $datetime1 , DateTime $datetime2 [, bool $absolute = false ] )

Returns the difference between two DateTime objects.

Parametry

datetime

The date to compare to.

absolute

Whether to return absolute difference.

Zwracane wartości

The DateInterval object representing the difference between the two dates lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::diff() example

Styl obiektowy

<?php
$datetime1 
= new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval $datetime1->diff($datetime2);
echo 
$interval->format('%R%a days');
?>

Styl proceduralny

<?php
$datetime1 
date_create('2009-10-11');
$datetime2 date_create('2009-10-13');
$interval date_diff($datetime1$datetime2);
echo 
$interval->format('%R%a days');
?>

Powyższe przykłady wyświetlą:

+2 days

Przykład #2 DateTime object comparison

Informacja:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

<?php
$date1 
= new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 $date2);
var_dump($date1 $date2);
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)
bool(false)

Zobacz też:

  • DateInterval::format() - Formats the interval
  • DateTime::add() - Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
  • DateTime::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object


DateTime::format

date_format

(PHP 5 >= 5.2.0)

DateTime::format -- date_formatReturns date formatted according to given format

Opis

Styl obiektowy

public string DateTime::format ( string $format )

Styl proceduralny

string date_format ( DateTime $object , string $format )

Returns date formatted according to given format.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

format

Format accepted by date().

Zwracane wartości

Returns the formatted date string on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::format() example

Styl obiektowy

<?php
$date 
= new DateTime('2000-01-01');
echo 
$date->format('Y-m-d H:i:s');
?>

Styl proceduralny

<?php
$date 
date_create('2000-01-01');
echo 
date_format($date'Y-m-d H:i:s');
?>

Powyższy przykład wyświetli:

2000-01-01 00:00:00

Notatki

This method does not use locales. All output is in English.

Zobacz też:

  • date() - Formatuje lokalny czas/datę


DateTime::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0)

DateTime::getLastErrors -- date_get_last_errorsReturns the warnings and errors

Opis

Styl obiektowy

public static array DateTime::getLastErrors ( void )

Styl proceduralny

array date_get_last_errors ( void )

Returns an array of 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

Styl obiektowy

<?php
try {
    
$date = new DateTime('asdfasdf');
} catch (
Exception $e) {
    
// For demonstration purposes only...
    
print_r(DateTime::getLastErrors());

    
// The real object oriented way to do this is
    // echo $e->getMessage();
}
?>

Styl proceduralny

<?php
$date 
date_create('asdfasdf');
print_r(date_get_last_errors());
?>

Powyższe przykłady wyświetlą:

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

date_offset_get

(PHP 5 >= 5.2.0)

DateTime::getOffset -- date_offset_getReturns the timezone offset

Opis

Styl obiektowy

public int DateTime::getOffset ( void )

Styl proceduralny

int date_offset_get ( DateTime $object )

Returns the timezone offset.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

Zwracane wartości

Returns the timezone offset in seconds from UTC on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::getOffset() example

Styl obiektowy

<?php
$winter 
= new DateTime('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTime('2008-06-21', new DateTimeZone('America/New_York'));

echo 
$winter->getOffset() . "\n";
echo 
$summer->getOffset() . "\n";
?>

Styl proceduralny

<?php
$winter 
date_create('2010-12-21'timezone_open('America/New_York'));
$summer date_create('2008-06-21'timezone_open('America/New_York'));

echo 
date_offset_get($winter) . "\n";
echo 
date_offset_get($summer) . "\n";
?>

Powyższe przykłady wyświetlą:

-18000
-14400

Note: -18000 = -5 hours, -14400 = -4 hours.



DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0)

DateTime::getTimestamp -- date_timestamp_getGets the Unix timestamp

Opis

Styl obiektowy

public int DateTime::getTimestamp ( void )

Styl proceduralny

int date_timestamp_get ( DateTime $object )

Gets the Unix timestamp.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the Unix timestamp representing the date.

Przykłady

Przykład #1 DateTime::getTimestamp() example

Styl obiektowy

<?php
$date 
= new DateTime();
echo 
$date->getTimestamp();
?>

Styl proceduralny

<?php
$date 
date_create();
echo 
date_timestamp_get($date);
?>

Powyższe przykłady wyświetlą coś podobnego do:

1272509157

Notatki

Using U as the parameter to DateTime::format() is an alternative when using PHP 5.2.

Zobacz też:



DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0)

DateTime::getTimezone -- date_timezone_getReturn time zone relative to given DateTime

Opis

Styl obiektowy

public DateTimeZone DateTime::getTimezone ( void )

Styl proceduralny

Return time zone relative to given DateTime.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create()

Zwracane wartości

Returns a DateTimeZone object on success lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::getTimezone() example

Styl obiektowy

<?php
$date 
= new DateTime(null, new DateTimeZone('Europe/London'));
$tz $date->getTimezone();
echo 
$tz->getName();
?>

Styl proceduralny

<?php
$date 
date_create(nulltimezone_open('Europe/London'));
$tz date_timezone_get($date);
echo 
timezone_name_get($tz);
?>

Powyższe przykłady wyświetlą:

Europe/London

Zobacz też:



DateTime::modify

date_modify

(PHP 5 >= 5.2.0)

DateTime::modify -- date_modifyAlters the timestamp

Opis

Styl obiektowy

public DateTime DateTime::modify ( string $modify )

Styl proceduralny

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(). Funkcja modyfikuje ten obiekt.

modify

Łańcuch daty/czasu. Prawidłowe formaty są wyjaśnione pod adresem Formaty daty i czasu.

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
5.3.6 Absolute date/time statements now take effect. Previously, only relative parts were used.
5.3.0Zmieniono zwracaną wartość w przypadku powodzenia z NULL na DateTime.

Przykłady

Przykład #1 DateTime::modify() example

Styl obiektowy

<?php
$date 
= new DateTime('2006-12-12');
$date->modify('+1 day');
echo 
$date->format('Y-m-d');
?>

Styl proceduralny

<?php
$date 
date_create('2006-12-12');
date_modify($date'+1 day');
echo 
date_format($date'Y-m-d');
?>

Powyższe przykłady wyświetlą:

2006-12-13

Przykład #2 Beware when adding or subtracting months

<?php
$date 
= new DateTime('2000-12-31');

$date->modify('+1 month');
echo 
$date->format('Y-m-d') . "\n";

$date->modify('+1 month');
echo 
$date->format('Y-m-d') . "\n";
?>

Powyższy przykład wyświetli:

2001-01-31
2001-03-03

Zobacz też:



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

date_date_set

(PHP 5 >= 5.2.0)

DateTime::setDate -- date_date_setSets the date

Opis

Styl obiektowy

public DateTime DateTime::setDate ( int $year , int $month , int $day )

Styl proceduralny

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(). Funkcja modyfikuje ten obiekt.

year

Year of the date.

month

Month of the date.

day

Day of the date.

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość w przypadku powodzenia z NULL na DateTime.

Przykłady

Przykład #1 DateTime::setDate() example

Styl obiektowy

<?php
$date 
= new DateTime();
$date->setDate(200123);
echo 
$date->format('Y-m-d');
?>

Styl proceduralny

<?php
$date 
date_create();
date_date_set($date200123);
echo 
date_format($date'Y-m-d');
?>

Powyższe przykłady wyświetlą:

2001-02-03

Przykład #2 Values exceeding ranges are added to their parent values

<?php
$date 
= new DateTime();

$date->setDate(2001228);
echo 
$date->format('Y-m-d') . "\n";

$date->setDate(2001229);
echo 
$date->format('Y-m-d') . "\n";

$date->setDate(2001143);
echo 
$date->format('Y-m-d') . "\n";
?>

Powyższy przykład wyświetli:

2001-02-28
2001-03-01
2002-02-03

Zobacz też:



DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0)

DateTime::setISODate -- date_isodate_setSets the ISO date

Opis

Styl obiektowy

public DateTime DateTime::setISODate ( int $year , int $week [, int $day = 1 ] )

Styl proceduralny

DateTime date_isodate_set ( DateTime $object , int $year , int $week [, int $day = 1 ] )

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(). Funkcja modyfikuje ten obiekt.

year

Year of the date.

week

Week of the date.

day

Offset from the first day of the week.

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość w przypadku powodzenia z NULL na DateTime.

Przykłady

Przykład #1 DateTime::setISODate() example

Styl obiektowy

<?php
$date 
= new DateTime();

$date->setISODate(20082);
echo 
$date->format('Y-m-d') . "\n";

$date->setISODate(200827);
echo 
$date->format('Y-m-d') . "\n";
?>

Styl proceduralny

<?php
$date 
date_create();

date_isodate_set($date20082);
echo 
date_format($date'Y-m-d') . "\n";

date_isodate_set($date200827);
echo 
date_format($date'Y-m-d') . "\n";
?>

Powyższe przykłady wyświetlą:

2008-01-07
2008-01-13

Przykład #2 Values exceeding ranges are added to their parent values

<?php
$date 
= new DateTime();

$date->setISODate(200827);
echo 
$date->format('Y-m-d') . "\n";

$date->setISODate(200828);
echo 
$date->format('Y-m-d') . "\n";

$date->setISODate(2008537);
echo 
$date->format('Y-m-d') . "\n";
?>

Powyższy przykład wyświetli:

2008-01-13
2008-01-14
2009-01-04

Przykład #3 Finding the month a week is in

<?php
$date 
= new DateTime();
$date->setISODate(200814);
echo 
$date->format('n');
?>

Powyższe przykłady wyświetlą:

3

Zobacz też:



DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0)

DateTime::setTime -- date_time_setSets the time

Opis

Styl obiektowy

public DateTime DateTime::setTime ( int $hour , int $minute [, int $second = 0 ] )

Styl proceduralny

DateTime date_time_set ( DateTime $object , int $hour , int $minute [, int $second = 0 ] )

Resets the current time of the DateTime object to a different time.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create(). Funkcja modyfikuje ten obiekt.

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość w przypadku powodzenia z NULL na DateTime.

Przykłady

Przykład #1 DateTime::setTime() example

Styl obiektowy

<?php
$date 
= new DateTime('2001-01-01');

$date->setTime(1455);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(145524);
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

Styl proceduralny

<?php
$date 
date_create('2001-01-01');

date_time_set($date1455);
echo 
date_format($date'Y-m-d H:i:s') . "\n";

date_time_set($date145524);
echo 
date_format($date'Y-m-d H:i:s') . "\n";
?>

Powyższe przykłady wyświetlą coś podobnego do:

2000-01-01 14:55:00
2000-01-01 14:55:24

Przykład #2 Values exceeding ranges are added to their parent values

<?php
$date 
= new DateTime('2001-01-01');

$date->setTime(145524);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(145565);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(146524);
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date->setTime(255524);
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

Powyższy przykład wyświetli:

2001-01-01 14:55:24
2001-01-01 14:56:05
2001-01-01 15:05:24
2001-01-02 01:55:24

Zobacz też:



DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0)

DateTime::setTimestamp -- date_timestamp_setSets the date and time based on an Unix timestamp

Opis

Styl obiektowy

public DateTime DateTime::setTimestamp ( int $unixtimestamp )

Styl proceduralny

DateTime date_timestamp_set ( DateTime $object , int $unixtimestamp )

Sets the date and time based on an Unix timestamp.

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create(). Funkcja modyfikuje ten obiekt.

unixtimestamp

Unix timestamp representing the date.

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::setTimestamp() example

Styl obiektowy

<?php
$date 
= new DateTime();
echo 
$date->format('U = Y-m-d H:i:s') . "\n";

$date->setTimestamp(1171502725);
echo 
$date->format('U = Y-m-d H:i:s') . "\n";
?>

Styl proceduralny

<?php
$date 
date_create();
echo 
date_format($date'U = Y-m-d H:i:s') . "\n";

date_timestamp_set($date1171502725);
echo 
date_format($date'U = Y-m-d H:i:s') . "\n";
?>

Powyższe przykłady wyświetlą coś podobnego do:

1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25

Notatki

Using the Unix timestamp format to construct a new DateTime object is an alternative when using PHP 5.2, as shown in the example below.

Przykład #2 DateTime::setTimestamp() alternative in PHP 5.2

<?php
$ts 
1171502725;
$date = new DateTime("@$ts");
echo 
$date->format('U = Y-m-d H:i:s') . "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

1171502725 = 2007-02-14 20:25:25

Zobacz też:



DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0)

DateTime::setTimezone -- date_timezone_setSets the time zone for the DateTime object

Opis

Styl obiektowy

public DateTime DateTime::setTimezone ( DateTimeZone $timezone )

Styl proceduralny

Parametry

object

Tylko styl proceduralny: Obiekt DateTime zwracany przez date_create(). Funkcja modyfikuje ten obiekt.

timezone

A DateTimeZone object representing the desired time zone.

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
5.3.0Zmieniono zwracaną wartość w przypadku powodzenia z NULL na DateTime.

Przykłady

Przykład #1 DateTime::setTimeZone() example

Styl obiektowy

<?php
$date 
= new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo 
$date->format('Y-m-d H:i:sP') . "\n";
?>

Styl proceduralny

<?php
$date 
date_create('2000-01-01'timezone_open('Pacific/Nauru'));
echo 
date_format($date'Y-m-d H:i:sP') . "\n";

date_timezone_set($datetimezone_open('Pacific/Chatham'));
echo 
date_format($date'Y-m-d H:i:sP') . "\n";
?>

Powyższe przykłady wyświetlą:

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

Zobacz też:



DateTime::sub

date_sub

(PHP 5 >= 5.3.0)

DateTime::sub -- date_sub Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object

Opis

Styl obiektowy

public DateTime DateTime::sub ( DateInterval $interval )

Styl proceduralny

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(). Funkcja modyfikuje ten obiekt.

interval

A DateInterval object

Zwracane wartości

Zwraca zmodyfikowany obiekt DateTime lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 DateTime::sub() example

Styl obiektowy

<?php
$date 
= new DateTime('2000-01-20');
$date->sub(new DateInterval('P10D'));
echo 
$date->format('Y-m-d') . "\n";
?>

Styl proceduralny

<?php
$date 
date_create('2000-01-20');
date_sub($datedate_interval_create_from_date_string('10 days'));
echo 
date_format($date'Y-m-d');
?>

Powyższe przykłady wyświetlą:

2000-01-10

Przykład #2 Further DateTime::sub() examples

<?php
$date 
= new DateTime('2000-01-20');
$date->sub(new DateInterval('PT10H30S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";

$date = new DateTime('2000-01-20');
$date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo 
$date->format('Y-m-d H:i:s') . "\n";
?>

Powyższy przykład wyświetli:

2000-01-19 13:59:30
1992-08-15 19:56:58

Przykład #3 Beware when subtracting months

<?php
$date 
= new DateTime('2001-04-30');
$interval = new DateInterval('P1M');

$date->sub($interval);
echo 
$date->format('Y-m-d') . "\n";

$date->sub($interval);
echo 
$date->format('Y-m-d') . "\n";
?>

Powyższy przykład wyświetli:

2001-03-30
2001-03-02

Notatki

DateTime::modify() is an alternative when using PHP 5.2.

Zobacz też:



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

(PHP 5 >= 5.2.0)

Wstęp

Representation of time zone.

Krótki opis klasy

DateTimeZone {
/* Stałe */
const integer AFRICA = 1 ;
const integer AMERICA = 2 ;
const integer ANTARCTICA = 4 ;
const integer ARCTIC = 8 ;
const integer ASIA = 16 ;
const integer ATLANTIC = 32 ;
const integer AUSTRALIA = 64 ;
const integer EUROPE = 128 ;
const integer INDIAN = 256 ;
const integer PACIFIC = 512 ;
const integer UTC = 1024 ;
const integer ALL = 2047 ;
const integer ALL_WITH_BC = 4095 ;
const integer PER_COUNTRY = 4096 ;
/* Metody */
public __construct ( string $timezone )
public array getLocation ( void )
public string getName ( void )
public int getOffset ( DateTime $datetime )
public array getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
public static array listAbbreviations ( void )
public static array listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )
}

Stałe predefiniowane

DateTimeZone::AFRICA

Africa time zones.

DateTimeZone::AMERICA

America time zones.

DateTimeZone::ANTARCTICA

Antarctica time zones.

DateTimeZone::ARCTIC

Arctic 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

timezone_open

(PHP 5 >= 5.2.0)

DateTimeZone::__construct -- timezone_openCreates new DateTimeZone object

Opis

Styl obiektowy

public DateTimeZone::__construct() ( string $timezone )

Styl proceduralny

DateTimeZone timezone_open ( string $timezone )

Creates new DateTimeZone object.

Parametry

timezone

One of timezones.

Zwracane wartości

Returns DateTimeZone on success. Styl proceduralny zwraca FALSE w przypadku niepowodzenia.

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

timezone_location_get

(PHP 5 >= 5.3.0)

DateTimeZone::getLocation -- timezone_location_getReturns location information for a timezone

Opis

Styl obiektowy

public array DateTimeZone::getLocation ( void )

Styl proceduralny

Returns location information for a timezone, including country code, latitude/longitude and comments.

Parametry

object

Tylko styl proceduralny: Obiekt DateTimeZone zwracany przez timezone_open()

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());
print_r(timezone_location_get($tz));
?>

Powyższy przykład wyświetli:

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] => 
)
Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] => 
)



DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0)

DateTimeZone::getName -- timezone_name_getReturns the name of the timezone

Opis

Styl obiektowy

public string DateTimeZone::getName ( void )

Styl proceduralny

string timezone_name_get ( DateTimeZone $object )

Returns the name of the timezone.

Parametry

object

The DateTimeZone for which to get a name.

Zwracane wartości

One of the timezone names in the list of timezones.



DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0)

DateTimeZone::getOffset -- timezone_offset_getReturns the timezone offset from GMT

Opis

Styl obiektowy

public int DateTimeZone::getOffset ( DateTime $datetime )

Styl proceduralny

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 lub FALSE w przypadku niepowodzenia.

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

timezone_transitions_get

(PHP 5 >= 5.2.0)

DateTimeZone::getTransitions -- timezone_transitions_getReturns all transitions for the timezone

Opis

Styl obiektowy

public array DateTimeZone::getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )

Styl proceduralny

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 lub FALSE w przypadku niepowodzenia.

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("Europe/London");
$transitions $timezone->getTransitions();
print_r(array_slice($transitions03));
?>

Powyższy przykład wyświetli coś podobnego do:

Array
(
    [0] => Array
        (
            [ts] => -9223372036854775808
            [time] => -292277022657-01-27T08:29:52+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [1] => Array
        (
            [ts] => -1691964000
            [time] => 1916-05-21T02:00:00+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [2] => Array
        (
            [ts] => -1680472800
            [time] => 1916-10-01T02:00:00+0000
            [offset] => 0
            [isdst] => 
            [abbr] => GMT
        )

)



DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0)

DateTimeZone::listAbbreviations -- timezone_abbreviations_listReturns associative array containing dst, offset and the timezone name

Opis

Styl obiektowy

public static array DateTimeZone::listAbbreviations ( void )

Styl proceduralny

Zwracane wartości

Returns array on success lub FALSE w przypadku niepowodzenia.

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

timezone_identifiers_list

(PHP 5 >= 5.2.0)

DateTimeZone::listIdentifiers -- timezone_identifiers_listReturns numerically index array with all timezone identifiers

Opis

Styl obiektowy

public static array DateTimeZone::listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Styl proceduralny

array timezone_identifiers_list ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )

Parametry

what

One of DateTimeZone class constants.

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 lub FALSE w przypadku niepowodzenia.

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/Asmara

Zobacz też:


Spis treści



The DateInterval class

(PHP 5 >= 5.3.0)

Wstęp

Representation of date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime's constructor supports.

Krótki opis klasy

DateInterval {
/* Właściwości */
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public integer $invert ;
public mixed $days ;
/* Metody */
public __construct ( string $interval_spec )
public static DateInterval createFromDateString ( string $time )
public string format ( string $format )
}

Właściwości

y

Number of years.

m

Number of months.

d

Number of days.

h

Number of hours.

i

Number of minutes.

s

Number of seconds.

invert

Is 1 if the interval is inverted and 0 otherwise. See DateInterval::format().

days

Total number of days between the starting and ending dates in a DateTime::diff() calculation. days will be FALSE in other circumstances.


DateInterval::__construct

(PHP 5 >= 5.3.0)

DateInterval::__constructCreates new DateInterval object

Opis

public 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');
var_dump($interval);

?>

Powyższy przykład wyświetli:

object(DateInterval)#1 (8) {
  ["y"]=>
  int(2)
  ["m"]=>
  int(0)
  ["d"]=>
  int(4)
  ["h"]=>
  int(6)
  ["i"]=>
  int(8)
  ["s"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
}

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. Each format character must be prefixed by a percent sign (%).
format character Description Example values
% Literal % %
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 1, 3, 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 -,

Zwracane wartości

Returns the formatted interval.

Notatki

Informacja:

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

Przykłady

Przykład #1 DateInterval example

<?php

$interval 
= new DateInterval('P2Y4DT6H8M');
echo 
$interval->format('%d days');

?>

Powyższy przykład wyświetli:

4 days

Przykład #2 DateInterval and carry over points

<?php

$interval 
= new DateInterval('P32D');
echo 
$interval->format('%d days');

?>

Powyższy przykład wyświetli:

32 days

Przykład #3 DateInterval and DateTime::diff() with the %a and %d modifiers

<?php

$january 
= new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval $february->diff($january);

// %a will output the total number of days.
echo $interval->format('%a total days')."\n";

// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');

?>

Powyższy przykład wyświetli:

31 total days
1 month, 0 days


Spis treści



The DatePeriod class

(PHP 5 >= 5.3.0)

Wstęp

Representation of date period.

Krótki opis klasy

DatePeriod implements Traversable {
/* Stałe */
const integer EXCLUDE_START_DATE = 1 ;
/* Metody */
public __construct ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
public __construct ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
public __construct ( string $isostr [, int $options ] )
}

Stałe predefiniowane

DatePeriod::EXCLUDE_START_DATE

Exclude start date, used in DatePeriod::__construct().


DatePeriod::__construct

(PHP 5 >= 5.3.0)

DatePeriod::__constructCreates new DatePeriod object

Opis

public DatePeriod::__construct() ( DateTime $start , DateInterval $interval , int $recurrences [, int $options ] )
public DatePeriod::__construct() ( DateTime $start , DateInterval $interval , DateTime $end [, int $options ] )
public 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_createAlias dla DateTime::__construct()

Opis

Ta funkcja jest aliasem dla: DateTime::__construct()



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)

  • Prior to PHP 5.4.0 only: Reading the TZ environment variable (if non empty)

  • Reading the value of the date.timezone ini option (if set)

  • Prior to PHP 5.4.0 only: Querying the host operating system (if supported and allowed by the OS). This uses an algorithm that has to guess the timezone. This is by no means going to work correctly for every situation. A warning is shown when this stage is reached. Do not rely on it to be guessed correctly, and set date.timezone to the correct timezone instead.

If none of the above succeed, date_default_timezone_get() will return a default timezone of UTC.

Zwracane wartości

Returns a string.

Rejestr zmian

Wersja Opis
5.4.0 The TZ environment variable is no longer used to guess the timezone.
5.4.0 The timezone is no longer guessed from information available through the operating system as the guessed timezone can not be relied on.

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 than 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 formatted according to the specified format

Opis

array date_parse_from_format ( string $format , string $date )

Returns associative array with detailed info about given date.

Parametry

format

Format accepted by DateTime::createFromFormat().

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] => 
)

Zobacz też:



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 lub FALSE w przypadku niepowodzenia.

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ż:



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 lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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 lub FALSE w przypadku niepowodzenia.

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 Przykład getdate()

<?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ę
  • idate() - Format a local time/date as integer
  • localtime() - Pobiera czas lokalny
  • 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ę
  • getdate() - Pobiera informację o dacie/czasie
  • 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()). Note that some of the format options available to strftime() may not have any effect within strptime(); the exact subset that are supported will vary based on the operating system and C library in use.

For more information about the format options, read the strftime() page.

Zwracane wartości

Returns an array lub FALSE w przypadku niepowodzenia.

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:

Internally, this function calls the strptime() function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended on PHP 5.3.0 and later.

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.

Informacja:

Prior to PHP 5.2.0, this function could return undefined behaviour. Notably, the "tm_sec", "tm_min" and "tm_hour" entries would return undefined values.

Zobacz też:



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

timezone_abbreviations_listAlias dla DateTimeZone::listAbbreviations()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::listAbbreviations()



timezone_identifiers_list

(PHP 5 >= 5.2.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. Defaults to -1, which means that whether the time zone has daylight saving or not is not taken into consideration when searching. If this is set to 1, then the gmtOffset is assumed to be an offset with daylight saving in effect; if 0, then gmtOffset is assumed to be an offset without daylight saving in effect. If abbr doesn't exist then the time zone is searched solely by the gmtOffset and isdst.

Zwracane wartości

Returns time zone name on success lub FALSE w przypadku niepowodzenia.

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

timezone_name_getAlias dla DateTimeZone::getName()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getName()



timezone_offset_get

(PHP 5 >= 5.2.0)

timezone_offset_getAlias dla DateTimeZone::getOffset()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::getOffset()



timezone_open

(PHP 5 >= 5.2.0)

timezone_openAlias dla DateTimeZone::__construct()

Opis

Ta funkcja jest aliasem dla: DateTimeZone::__construct()



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



Supported Date and Time Formats

Spis treści

This section describes all the different formats that the strtotime(), DateTime and date_create() parser understands. The formats are grouped by section. In most cases formats from different sections can be used in the same date/time string. For each of the supported formats, one or more examples are given, as well as a description for the format. Characters in single quotes in the formats are case-insensitive ('t' could be t or T), characters in double quotes are case-sensitive ("T" is only T).


Time Formats

Used Symbols
Description Formats Examples
frac . [0-9]+ ".21342", ".85"
hh "0"?[1-9] | "1"[0-2] "04", "7", "12"
HH [01][0-9] | "2"[0-4] "04", "7", "19"
meridian [AaPp] .? [Mm] .? [\0\t ] "A.m.", "pM", "am."
MM [0-5][0-9] "00", "12", "59"
II [0-5][0-9] "00", "12", "59"
space [ \t]  
tz "("? [A-Za-z]{1,6} ")"? | [A-Z][a-z]+([_/][A-Z][a-z]+)+ "CEST", "Europe/Amsterdam", "America/Indiana/Knox"
tzcorrection "GMT"? [+-] hh ":"? MM? "+0400", "GMT-07:00", "-07:00"
12 Hour Notation
Description Format Examples
Hour only, with meridian hh space? meridian "4 am", "5PM"
Hour and minutes, with meridian hh [.:] MM space? meridian "4:08 am", "7:19P.M."
Hour, minutes and seconds, with meridian hh [.:] MM [.:] II space? meridian "4:08:37 am", "7:19:19P.M."
MS SQL (Hour, minutes, seconds and fraction with meridian), PHP 5.3 and later only hh ":" MM ":" II [.:] [0-9]+ meridian "4:08:39:12313am"
24 Hour Notation
Description Format Examples
Hour and minutes 't'? HH [.:] MM "04:08", "19.19", "T23:43"
Hour and minutes, no colon 't'? HH MM "0408", "t1919", "T2343"
Hour, minutes and seconds 't'? HH [.:] MM [.:] II "04.08.37", "t19:19:19"
Hour, minutes and seconds, no colon 't'? HH MM II "040837", "T191919"
Hour, minutes, seconds and timezone 't'? HH [.:] MM [.:] II space? ( tzcorrection | tz ) "040837CEST", "T191919-0700"
Hour, minutes, seconds and fraction 't'? HH [.:] MM [.:] II frac "04.08.37.81412", "19:19:19.532453"
Time zone information tz | tzcorrection "CEST", "Europe/Amsterdam", "+0430", "GMT-06:00"


Date Formats

Used Symbols
Description Format Examples
daysuf "st" | "nd" | "rd" | "th"  
dd ([0-2]?[0-9] | "3"[01]) daysuf? "7th", "22nd", "31"
DD "0" [0-9] | [1-2][0-9] | "3" [01] "07", "31"
m 'january' | 'february' | 'march' | 'april' | 'may' | 'june' | 'july' | 'august' | 'september' | 'october' | 'november' | 'december' | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII"  
M 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec'  
mm "0"? [0-9] | "1"[0-2] "0", "04", "7", "12"
MM "0" [0-9] | "1"[0-2] "00", "04", "07", "12"
y [0-9]{1,4} "00", "78", "08", "8", "2008"
yy [0-9]{2} "00", "08", "78"
YY [0-9]{4} "2000", "2008", "1978"
Localized Notations
Description Format Examples
American month and day mm "/" dd "5/12", "10/27"
American month, day and year mm "/" dd "/" y "12/22/78", "1/17/2006", "1/17/6"
Four digit year, month and day with slashes YY "/" mm "/" dd "2008/6/30", "1978/12/22"
Four digit year and month (GNU) YY "-" mm "2008-6", "2008-06", "1978-12"
Year, month and day with dashes y "-" mm "-" dd "2008-6-30", "78-12-22", "8-6-21"
Day, month and four digit year, with dots, tabs or dashes dd [.\t-] mm [.-] YY "30-6-2008", "22.12\t1978"
Day, month and two digit year, with dots or tabs dd [.\t] mm "." yy "30.6.08", "22\t12\t78"
Day, textual month and year dd ([ \t.-])* m ([ \t.-])* y "30-June 2008", "22DEC78", "14 III 1879"
Textual month and four digit year (Day reset to 1) m ([ \t.-])* YY "June 2008", "DEC1978", "March 1879"
Four digit year and textual month (Day reset to 1) YY ([ \t.-])* m "2008 June", "1978-XII", "1879.MArCH"
Textual month, day and year m ([ .\t-])* dd [,.stndrh\t ]+ y "July 1st, 2008", "April 17, 1790", "May.9,78"
Textual month and day m ([ .\t-])* dd [,.stndrh\t ]* "July 1st,", "Apr 17", "May.9"
Day and textual month d ([ .\t-])* m "1 July", "17 Apr", "9.May"
Month abbreviation, day and year M "-" DD "-" y "May-09-78", "Apr-17-1790"
Year, month abbreviation and day y "-" M "-" DD "78-Dec-22", "1814-MAY-17"
Year (and just the year) YY "1978", "2008"
Textual month (and just the month) m "March", "jun", "DEC"
ISO8601 Notations
Description Format Examples
Eight digit year, month and day YY MM DD "15810726", "19780417", "18140517"
Four digit year, month and day with slashes YY "/" MM "/" DD "2008/06/30", "1978/12/22"
Two digit year, month and day with dashes yy "-" MM "-" DD "08-06-30", "78-12-22"
Four digit year with optional sign, month and day [+-]? YY "-" MM "-" DD "-0002-07-26", "+1978-04-17", "1814-05-17"

Informacja:

For the y and yy formats, years below 100 are handled in a special way when the y or yy symbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that "00-01-01" is interpreted as "2000-01-01".

Informacja:

The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy) only works for the year values 61 (inclusive) to 99 (inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has precedence.

Informacja:

The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

Informacja:

It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).

It is also possible to underflow the mm and MM formats with the value 0. A month value of 0 means December of the previous year. As example "2008-00-22" is equivalent to "2007-12-22".

If you combine the previous two facts and underflow both the day and the month, the following happens: "2008-00-00" first gets converted to "2007-12-00" which then gets converted to "2007-11-30". This also happens with the string "0000-00-00", which gets transformed into "-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).



Compound Formats

Used Symbols
Description Formats Examples
DD "0" [0-9] | [1-2][0-9] | "3" [01] "02", "12", "31"
doy "00"[1-9] | "0"[1-9][0-9] | [1-2][0-9][0-9] | "3"[0-5][0-9] | "36"[0-6] "36"[0-6] "000", "012", "366"
frac . [0-9]+ ".21342", ".85"
hh "0"?[1-9] | "1"[0-2] "04", "7", "12"
HH [01][0-9] | "2"[0-4] "04", "7", "19"
meridian [AaPp] .? [Mm] .? [\0\t ] "A.m.", "pM", "am."
ii [0-5][0-9] "04", "8", "59"
II [0-5][0-9] "04", "08", "59"
M 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec'  
MM [0-5][0-9] "00", "12", "59"
space [ \t]  
ss [0-5][0-9] "04", "8", "59"
SS [0-5][0-9] "04", "08", "59"
W "0"[1-9] | [1-4][0-9] | "5"[0-3] "05", "17", "53"
tzcorrection "GMT"? [+-] hh ":"? MM? "+0400", "GMT-07:00", "-07:00"
YY [0-9]{4} "2000", "2008", "1978"
Localized Notations
Description Format Examples
Common Log Format dd "/" M "/" YY : HH ":" II ":" SS space tzcorrection "10/Oct/2000:13:55:36 -0700"
EXIF YY ":" MM ":" DD " " HH ":" II ":" SS "2008:08:07 18:11:31"
ISO year with ISO week YY "-"? "W" W "2008W27", "2008-W28"
ISO year with ISO week and day YY "-"? "W" W "-"? [0-7] "2008W273", "2008-W28-3"
MySQL YY "-" MM "-" DD " " HH ":" II ":" SS "2008-08-07 18:11:31"
PostgreSQL: Year with day-of-year YY "."? doy "2008.197", "2008197"
SOAP YY "-" MM "-" DD "T" HH ":" II ":" SS frac tzcorrection? "2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00"
Unix Timestamp "@" "-"? [0-9]+ "@1215282385"
XMLRPC YY MM DD "T" hh ":" II ":" SS "20080701T22:38:07", "20080701T9:38:07"
XMLRPC (Compact) YY MM DD 't' hh II SS "20080701t223807", "20080701T093807"
WDDX YY "-" mm "-" dd "T" hh ":" ii ":" ss "2008-7-1T9:3:37"

Informacja:

The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".

The "T" in the SOAP, XMRPC and WDDX formats is case-sensitive, you can only use the upper case "T".

The "Unix Timestamp" format sets the timezone to UTC.



Relative Formats

Used Symbols
Description Format
dayname 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun'
daytext 'weekday' | 'weekdays'
number [+-]?[0-9]+
ordinal 'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' | 'twelfth' | 'next' | 'last' | 'previous' | 'this'
reltext 'next' | 'last' | 'previous' | 'this'
space [ \t]+
unit (('sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' | 'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks' | daytext
Day-based Notations
Format Description Examples
'yesterday' Midnight of yesterday "yesterday 14:00"
'midnight' The time is set to 00:00:00  
'today' The time is set to 00:00:00  
'now' Now - this is simply ignored  
'noon' The time is set to 12:00:00 "yesterday noon"
'tomorrow' Midnight of tomorrow  
'back of' hour 15 minutes past the specified hour "back of 7pm", "back of 15"
'front of' hour 15 minutes before the specified hour "front of 5am", "front of 23"
'first day' ' of'? Sets the day of the first of the current month. This phrase is best used together with a month name following it. "first day of January 2008"
'last day' ' of'? Sets the day to the last day of the current month. This phrase is best used together with a month name following it. "last day of next month"
ordinal space dayname space 'of' Calculates the x-th week day of the current month. "first sat of July 2008"
'last' space dayname space 'of' Calculates the last week day of the current month. "last sat of July 2008"
number space? (unit | 'week') Handles relative time items where the value is a number. "+5 weeks", "12 day", "-7 weekdays"
ordinal space unit Handles relative time items where the value is text. "fifth day", "second month"
'ago' Negates all the values of previously found relative time items. "2 days ago", "8 days ago 14:00", "2 months 5 days ago", "2 months ago 5 days", "2 days ago ago"
dayname Moves to the next day of this name. "Monday"
reltext space 'week' Handles the special format "weekday + last/this/next week". "Monday next week"

Informacja:

Relative statements are always processed after non-relative statements. This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.

Exceptions to this rule are: "yesterday", "midnight", "today", "noon" and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are different. Considering today's date of "July 23rd, 2008" the first one produces "2008-07-24 11:00" where as the second one produces "2008-07-24 00:00". The reason for this is that those five statements directly influence the current time.

Informacja:

Observe the following remarks when the current day-of-week is the same as the day-of-week used in the date/time string. The current day-of-week could have been (re-)calculated by non-relative parts of the date/time string however.

  1. "dayname" does not advance to another day. (Example: "Wed July 23rd, 2008" means "2008-07-23").
  2. "number dayname" does not advance to another day. (Example: "1 wednesday july 23rd, 2008" means "2008-07-23").
  3. "number week dayname" will first add the number of weeks, but does not advance to another day. In this case "number week" and "dayname" are two distinct blocks. (Example: "+1 week wednesday july 23rd, 2008" means "2008-07-30").
  4. "ordinal dayname" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").
  5. "number week ordinal dayname" will first add the number of weeks, and then advances to another day. In this case "number week" and "ordinal dayname" are two distinct blocks. (Example: "+1 week first wednesday july 23rd, 2008" means "2008-08-06").
  6. "ordinal dayname 'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.

  1. It sets the day-of-month to 1.
  2. "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").
  3. "ordinal dayname " does advance to another day. (Example: "first tuesday july 2008" means "2008-07-08", see also point 4 in the list above).
  4. "'last' dayname 'of' " takes the last dayname of the current month. (Example: "last wed of july 2008" means "2008-07-30")
  5. "'last' dayname" takes the last dayname from the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").

Informacja:

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.




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: Ta lista jest oparta o wersję bazy danych stref czasowych 2012.2.


Afryka

Afryka
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/Juba 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  


Ameryka

Ameryka
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/Bahia_Banderas 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/Creston
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/Kralendijk America/La_Paz
America/Lima America/Los_Angeles America/Louisville America/Lower_Princes America/Maceio
America/Managua America/Manaus America/Marigot America/Martinique America/Matamoros
America/Mazatlan America/Mendoza America/Menominee America/Merida America/Metlakatla
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/Beulah America/North_Dakota/Center America/North_Dakota/New_Salem
America/Ojinaga 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/Santa_Isabel America/Santarem America/Santiago
America/Santo_Domingo America/Sao_Paulo America/Scoresbysund America/Shiprock America/Sitka
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  


Antarktyda

Antarktyda
Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Macquarie Antarctica/Mawson
Antarctica/McMurdo Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa
Antarctica/Vostok        


Arktyka

Arktyka
Arctic/Longyearbyen


Azja

Azja
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/Hebron 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  


Ocean Atlantycki

Ocean Atlantycki
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    


Europa

Europa
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    


Ocean Indyjski

Ocean Indyjski
Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte
Indian/Reunion        


Ocean Spokojny

Ocean Spokojny
Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Chuuk 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/Pohnpei
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      


Inne

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






Rozszerzenia wiersza poleceń


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

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/ncurses.

Wide character CRT screen handling (ncursesw) support was added in version 1.0.1 of this PECL extension.



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

y

This will be set to the window height

x

This will be set to the window width

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 pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

bg

The background color for the color pair. May be one of the pre-defined colors or one defined by ncurses_init_color() if the terminal has color changing capabilities.

Zwracane wartości

Returns -1 if the function was successful, and 0 if ncurses or color support were not initialized.

Notatki

Note that color changing capabilities are not required for defining color pairs of pre-existing colors, but only for changing definitions (red, green, and blue components) of colors themselves per ncurses_init_color().

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_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_initInitialize ncurses

Opis

void ncurses_init ( void )

Initializes the ncurses interface. This function must be used before any other ncurses function call.

Note that ncurses_end() must be called before exiting from the program, or the terminal will not be restored to its proper non-visual mode.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Nie jest zwracana żadna wartość.

Zobacz też:



ncurses_insch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_inschInsert character moving rest of line including character at current position

Opis

int ncurses_insch ( 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_insdelln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insdellnInsert lines before current line scrolling down (negative numbers delete and scroll up)

Opis

int ncurses_insdelln ( int $count )
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

count



ncurses_insertln

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insertlnInsert a line, move rest of screen down

Opis

int ncurses_insertln ( 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.

Inserts a new line above the current line. The bottom line will be lost.



ncurses_insstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_insstrInsert string at current position, moving rest of line right

Opis

int ncurses_insstr ( 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_instr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_instrReads string from terminal screen

Opis

int ncurses_instr ( string &$buffer )
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.

Reads a string from the terminal screen and returns the number of characters read from the current character position until end of line.

Parametry

buffer

The characters. Attributes will be stripped.

Zwracane wartości

Returns the number of characters.



ncurses_isendwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_isendwinNcurses is in endwin mode, normal screen output may be performed

Opis

bool ncurses_isendwin ( 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 if ncurses is in endwin mode.

Zwracane wartości

Returns TRUE, if ncurses_end() has been called without any subsequent calls to ncurses_wrefresh(), FALSE otherwise.

Zobacz też:



ncurses_keyok

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keyokEnable or disable a keycode

Opis

int ncurses_keyok ( int $keycode , bool $enable )
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

enable



ncurses_keypad

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_keypadTurns keypad on or off

Opis

int ncurses_keypad ( resource $window , bool $bf )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

bf



ncurses_killchar

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_killcharReturns current line kill character

Opis

string ncurses_killchar ( 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 line kill character.

Zwracane wartości

Returns the kill character, as a string.

Zobacz też:



ncurses_longname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_longnameReturns terminals description

Opis

string ncurses_longname ( 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 a verbose description of the terminal.

Zwracane wartości

Returns the description, as a string truncated to 128 characters. On errors, returns NULL.

Zobacz też:



ncurses_meta

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_metaEnables/Disable 8-bit meta key information

Opis

int ncurses_meta ( resource $window , bool $8bit )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

8bit



ncurses_mouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouse_trafoTransforms coordinates

Opis

bool ncurses_mouse_trafo ( int &$y , int &$x , bool $toscreen )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

y

x

toscreen



ncurses_mouseinterval

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mouseintervalSet timeout for mouse button clicks

Opis

int ncurses_mouseinterval ( 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_mousemask

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mousemaskSets mouse options

Opis

int ncurses_mousemask ( int $newmask , int &$oldmask )
Ostrzeżenie

Ta funkcja jest w stadium EKSPERYMENTALNYM. Oznacza to, że zachowanie funkcji, jej nazwa, w zasadzie wszystko udokumentowane tutaj może zostać zmienione w przyszłych wersjach PHP bez wcześniejszego uprzedzenia. Używaj tej funkcji na własne ryzyko.

Sets mouse events to be reported. By default no mouse events will be reported.

Mouse events are represented by NCURSES_KEY_MOUSE in the ncurses_wgetch() input stream. To read the event data and pop the event of queue, call ncurses_getmouse().

Parametry

newmask

Mouse mask options can be set with the following predefined constants:

  • NCURSES_BUTTON1_PRESSED

  • NCURSES_BUTTON1_RELEASED

  • NCURSES_BUTTON1_CLICKED

  • NCURSES_BUTTON1_DOUBLE_CLICKED

  • NCURSES_BUTTON1_TRIPLE_CLICKED

  • NCURSES_BUTTON2_PRESSED

  • NCURSES_BUTTON2_RELEASED

  • NCURSES_BUTTON2_CLICKED

  • NCURSES_BUTTON2_DOUBLE_CLICKED

  • NCURSES_BUTTON2_TRIPLE_CLICKED

  • NCURSES_BUTTON3_PRESSED

  • NCURSES_BUTTON3_RELEASED

  • NCURSES_BUTTON3_CLICKED

  • NCURSES_BUTTON3_DOUBLE_CLICKED

  • NCURSES_BUTTON3_TRIPLE_CLICKED

  • NCURSES_BUTTON4_PRESSED

  • NCURSES_BUTTON4_RELEASED

  • NCURSES_BUTTON4_CLICKED

  • NCURSES_BUTTON4_DOUBLE_CLICKED

  • NCURSES_BUTTON4_TRIPLE_CLICKED

  • NCURSES_BUTTON_SHIFT>

  • NCURSES_BUTTON_CTRL

  • NCURSES_BUTTON_ALT

  • NCURSES_ALL_MOUSE_EVENTS

  • NCURSES_REPORT_MOUSE_POSITION

As a side effect, setting a zero mousemask in newmask turns off the mouse pointer. Setting a non zero value turns mouse pointer on.

oldmask

This will be set to the previous value of the mouse event mask.

Zwracane wartości

Returns a mask to indicated which of the in parameter newmask specified mouse events can be reported. On complete failure, it returns 0.

Przykłady

Przykład #1 ncurses_mousemask() example

<?php
$newmask 
NCURSES_BUTTON1_CLICKED NCURSES_BUTTON1_RELEASED;
$mask ncurses_mousemask($newmask$oldmask);
if (
$mask $newmask){
    
printf("All specified mouse options will be supported\n");
}
?>

Zobacz też:



ncurses_move_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_move_panelMoves a panel so that its upper-left corner is at [startx, starty]

Opis

int ncurses_move_panel ( resource $panel , int $startx , int $starty )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel

startx

starty



ncurses_move

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_moveMove output position

Opis

int ncurses_move ( 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.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

y

x



ncurses_mvaddch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchMove current position and add character

Opis

int ncurses_mvaddch ( int $y , int $x , int $c )
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

y

x

c



ncurses_mvaddchnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchnstrMove position and add attributed string with specified length

Opis

int ncurses_mvaddchnstr ( int $y , int $x , 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

y

x

s

n



ncurses_mvaddchstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddchstrMove position and add attributed string

Opis

int ncurses_mvaddchstr ( int $y , int $x , 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

y

x

s



ncurses_mvaddnstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddnstrMove position and add string with specified length

Opis

int ncurses_mvaddnstr ( int $y , int $x , 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

y

x

s

n



ncurses_mvaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvaddstrMove position and add string

Opis

int ncurses_mvaddstr ( int $y , int $x , 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

y

x

s



ncurses_mvcur

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvcurMove cursor immediately

Opis

int ncurses_mvcur ( int $old_y , int $old_x , int $new_y , int $new_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.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

old_y

old_x

new_y

new_x



ncurses_mvdelch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvdelchMove position and delete character, shift rest of line left

Opis

int ncurses_mvdelch ( 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.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

y

x



ncurses_mvgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvgetchMove position and get character at new position

Opis

int ncurses_mvgetch ( 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.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

y

x



ncurses_mvhline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvhlineSet new position and draw a horizontal line using an attributed character and max. n characters long

Opis

int ncurses_mvhline ( int $y , int $x , int $attrchar , 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

y

x

attrchar

n



ncurses_mvinch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvinchMove position and get attributed character at new position

Opis

int ncurses_mvinch ( 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.

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

y

x



ncurses_mvvline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvvlineSet new position and draw a vertical line using an attributed character and max. n characters long

Opis

int ncurses_mvvline ( int $y , int $x , int $attrchar , 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

y

x

attrchar

n



ncurses_mvwaddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_mvwaddstrAdd string at new position in window

Opis

int ncurses_mvwaddstr ( resource $window , int $y , int $x , 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

window

y

x

text



ncurses_napms

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_napmsSleep

Opis

int ncurses_napms ( 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_new_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_new_panelCreate a new panel and associate it with window

Opis

resource ncurses_new_panel ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_newpad

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newpadCreates a new pad (window)

Opis

resource ncurses_newpad ( int $rows , int $cols )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

rows

cols



ncurses_newwin

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_newwinCreate a new window

Opis

resource ncurses_newwin ( int $rows , int $cols , 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.

Creates a new window to draw elements in.

When creating additional windows, remember to use ncurses_getmaxyx() to check for available space, as terminal size is individual and may vary.

Parametry

rows

Number of rows

cols

Number of columns

y

y-coordinate of the origin

x

x-coordinate of the origin

Zwracane wartości

Returns a resource ID for the new window.



ncurses_nl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nlTranslate newline and carriage return / line feed

Opis

bool ncurses_nl ( 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_nocbreak

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nocbreakSwitch terminal to cooked mode

Opis

bool ncurses_nocbreak ( 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 terminal to normal (cooked) mode. Initially the terminal may or may not in cbreak mode as the mode is inherited. Therefore a program should call ncurses_cbreak() and ncurses_nocbreak() explicitly.

Zwracane wartości

Returns TRUE if any error occurred, otherwise FALSE.

Zobacz też:



ncurses_noecho

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noechoSwitch off keyboard input echo

Opis

bool ncurses_noecho ( 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.

Prevents echoing of user typed characters.

Zwracane wartości

Returns TRUE if any error occurred, FALSE otherwise.

Zobacz też:



ncurses_nonl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_nonlDo not translate newline and carriage return / line feed

Opis

bool ncurses_nonl ( 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_noqiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_noqiflushDo not flush on signal characters

Opis

void ncurses_noqiflush ( 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_noraw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_norawSwitch terminal out of raw mode

Opis

bool ncurses_noraw ( 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.

Switches the terminal out of raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Zwracane wartości

Returns TRUE if any error occurred, otherwise FALSE.

Zobacz też:



ncurses_pair_content

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pair_contentRetrieves foreground and background colors of a color pair

Opis

int ncurses_pair_content ( int $pair , int &$f , int &$b )

Retrieves the foreground and background colors that constitute the given color pair. Terminal color capabilities must be initialized with ncurses_start_color() prior to calling this function.

Parametry

pair

The number of the color pair to retrieve information for.

f

A reference to which to return the foreground color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

b

A reference to which to return the background color of the color pair. The information returned will be a color number referring to one of the pre-defined colors or a color defined previously by ncurses_init_color() if the terminal supports color changing.

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_panel_above

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_aboveReturns the panel above panel

Opis

resource ncurses_panel_above ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel

Zwracane wartości

If panel is null, returns the bottom panel in the stack.



ncurses_panel_below

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_belowReturns the panel below panel

Opis

resource ncurses_panel_below ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel

Parametry

If panel is null, returns the top panel in the stack.



ncurses_panel_window

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_panel_windowReturns the window associated with panel

Opis

resource ncurses_panel_window ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel



ncurses_pnoutrefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_pnoutrefreshCopies a region from a pad into the virtual screen

Opis

int ncurses_pnoutrefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol



ncurses_prefresh

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_prefreshCopies a region from a pad into the virtual screen

Opis

int ncurses_prefresh ( resource $pad , int $pminrow , int $pmincol , int $sminrow , int $smincol , int $smaxrow , int $smaxcol )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

pad

pminrow

pmincol

sminrow

smincol

smaxrow

smaxcol



ncurses_putp

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_putpApply padding information to the string and output it

Opis

int ncurses_putp ( 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_qiflush

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_qiflushFlush on signal characters

Opis

void ncurses_qiflush ( 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_raw

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_rawSwitch terminal into raw mode

Opis

bool ncurses_raw ( 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.

Places the terminal in raw mode. Raw mode is similar to cbreak mode, in that characters typed are immediately passed through to the user program. The differences that are that in raw mode, the interrupt, quit, suspend and flow control characters are all passed through uninterpreted, instead of generating a signal.

Zwracane wartości

Returns TRUE if any error occurred, otherwise FALSE.

Zobacz też:



ncurses_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_refreshRefresh screen

Opis

int ncurses_refresh ( 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_replace_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_replace_panelReplaces the window associated with panel

Opis

int ncurses_replace_panel ( resource $panel , resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel

window



ncurses_reset_prog_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_prog_modeResets the prog mode saved by def_prog_mode

Opis

int ncurses_reset_prog_mode ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_reset_shell_mode

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_reset_shell_modeResets the shell mode saved by def_shell_mode

Opis

int ncurses_reset_shell_mode ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_resetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_resettyRestores saved terminal state

Opis

bool ncurses_resetty ( 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.

Restores the terminal state, which was previously saved by calling ncurses_savetty().

Zwracane wartości

Always returns FALSE.

Zobacz też:



ncurses_savetty

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_savettySaves terminal state

Opis

bool ncurses_savetty ( 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 state. The saved terminal state can be restored with ncurses_resetty().

Zwracane wartości

Always returns FALSE.

Zobacz też:



ncurses_scr_dump

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_dumpDump screen content to file

Opis

int ncurses_scr_dump ( string $filename )
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

filename



ncurses_scr_init

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_initInitialize screen from file dump

Opis

int ncurses_scr_init ( string $filename )
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

filename



ncurses_scr_restore

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_restoreRestore screen from file dump

Opis

int ncurses_scr_restore ( string $filename )
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

filename



ncurses_scr_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scr_setInherit screen from file dump

Opis

int ncurses_scr_set ( string $filename )
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

filename



ncurses_scrl

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_scrlScroll window content up or down without changing current position

Opis

int ncurses_scrl ( int $count )
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

count



ncurses_show_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_show_panelPlaces an invisible panel on top of the stack, making it visible

Opis

int ncurses_show_panel ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel



ncurses_slk_attr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attrReturns current soft label key attribute

Opis

int ncurses_slk_attr ( 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 soft label key attribute.

Zwracane wartości

The attribute, as an integer.



ncurses_slk_attroff

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attroffTurn off the given attributes for soft function-key labels

Opis

int ncurses_slk_attroff ( int $intarg )
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

intarg



ncurses_slk_attron

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attronTurn on the given attributes for soft function-key labels

Opis

int ncurses_slk_attron ( int $intarg )
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

intarg



ncurses_slk_attrset

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_attrsetSet given attributes for soft function-key labels

Opis

int ncurses_slk_attrset ( int $intarg )
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

intarg



ncurses_slk_clear

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_clearClears soft labels from screen

Opis

bool ncurses_slk_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.

The function ncurses_slk_clear() clears soft label keys from screen.

Zwracane wartości

Returns TRUE on errors, FALSE otherwise.



ncurses_slk_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_colorSets color for soft label keys

Opis

int ncurses_slk_color ( int $intarg )
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

intarg



ncurses_slk_init

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_initInitializes soft label key functions

Opis

bool ncurses_slk_init ( int $format )
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.

Initializes soft label key functions

This function must be called before ncurses_init() or ncurses_newwin() is called.

Parametry

format

If ncurses_init() eventually uses a line from stdscr to emulate the soft labels, then this parameter determines how the labels are arranged of the screen.

0 indicates a 3-2-3 arrangement of the labels, 1 indicates a 4-4 arrangement and 2 indicates the PC like 4-4-4 mode, but in addition an index line will be created.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



ncurses_slk_noutrefresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_noutrefreshCopies soft label keys to virtual screen

Opis

bool ncurses_slk_noutrefresh ( 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_slk_refresh

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_refreshCopies soft label keys to screen

Opis

int ncurses_slk_refresh ( 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.

Copies soft label keys from virtual screen to physical screen.



ncurses_slk_restore

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_restoreRestores soft label keys

Opis

int ncurses_slk_restore ( 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.

Restores the soft label keys after ncurses_slk_clear() has been performed.



ncurses_slk_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_setSets function key labels

Opis

bool ncurses_slk_set ( int $labelnr , string $label , int $format )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

labelnr

label

format



ncurses_slk_touch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_slk_touchForces output when ncurses_slk_noutrefresh is performed

Opis

int ncurses_slk_touch ( 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.

Forces all the soft labels to be output the next time a ncurses_slk_noutrefresh() is performed.



ncurses_standend

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standendStop using 'standout' attribute

Opis

int ncurses_standend ( 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_standout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_standoutStart using 'standout' attribute

Opis

int ncurses_standout ( 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_start_color

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_start_colorInitializes color functionality

Opis

int ncurses_start_color ( void )

Initializes color functionality in ncurses. This function must be called before any color manipulation functions are called and after ncurses_init() is called. It is good practice to call this function right after ncurses_init().

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns 0 on success, or -1 if the color table could not be allocated or ncurses was not initialized.

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_termattrs

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termattrsReturns a logical OR of all attribute flags supported by terminal

Opis

bool ncurses_termattrs ( 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_termname

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_termnameReturns terminals (short)-name

Opis

string ncurses_termname ( 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 terminals shortname.

Zwracane wartości

Returns the shortname of the terminal, truncated to 14 characters. On errors, returns NULL.

Zobacz też:



ncurses_timeout

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_timeoutSet timeout for special key sequences

Opis

void ncurses_timeout ( int $millisec )
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

millisec



ncurses_top_panel

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_top_panelMoves a visible panel to the top of the stack

Opis

int ncurses_top_panel ( resource $panel )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

panel



ncurses_typeahead

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_typeaheadSpecify different filedescriptor for typeahead checking

Opis

int ncurses_typeahead ( int $fd )
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

fd



ncurses_ungetch

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetchPut a character back into the input stream

Opis

int ncurses_ungetch ( 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_ungetmouse

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_ungetmousePushes mouse event to queue

Opis

bool ncurses_ungetmouse ( 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.

Pushes a KEY_MOUSE event onto the unput queue and associates with this event the given state sata and screen-relative character cell coordinates, specified in mevent.

Parametry

mevent

An associative array specifying the event options:

  • "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 on success, TRUE otherwise.

Zobacz też:



ncurses_update_panels

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_update_panelsRefreshes the virtual screen to reflect the relations between panels in the stack

Opis

void ncurses_update_panels ( void )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.



ncurses_use_default_colors

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_default_colorsAssign terminal default colors to color id -1

Opis

bool ncurses_use_default_colors ( 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_use_env

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_envControl use of environment information about terminal size

Opis

void ncurses_use_env ( bool $flag )
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

flag



ncurses_use_extended_names

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_use_extended_namesControl use of extended names in terminfo descriptions

Opis

int ncurses_use_extended_names ( bool $flag )
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

flag



ncurses_vidattr

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vidattrDisplay the string on the terminal in the video attribute mode

Opis

int ncurses_vidattr ( int $intarg )
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

intarg



ncurses_vline

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_vlineDraw a vertical line at current position using an attributed character and max. n characters long

Opis

int ncurses_vline ( 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_waddch

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddchAdds character at current position in a window and advance cursor

Opis

int ncurses_waddch ( resource $window , int $ch )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

ch



ncurses_waddstr

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_waddstrOutputs text at current postion in window

Opis

int ncurses_waddstr ( resource $window , string $str [, int $n ] )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

str

n



ncurses_wattroff

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattroffTurns off attributes for a window

Opis

int ncurses_wattroff ( resource $window , int $attrs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

attrs



ncurses_wattron

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattronTurns on attributes for a window

Opis

int ncurses_wattron ( resource $window , int $attrs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

attrs



ncurses_wattrset

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wattrsetSet the attributes for a window

Opis

int ncurses_wattrset ( resource $window , int $attrs )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

attrs



ncurses_wborder

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wborderDraws a border around the window using attributed characters

Opis

int ncurses_wborder ( resource $window , 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 passed window.

Use ncurses_border() for borders around the main window.

Parametry

Each parameter expects 0 to draw a line and 1 to skip it.

window

The window on which we operate

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_border() - Draw a border around the screen using attributed characters



ncurses_wclear

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wclearClears window

Opis

int ncurses_wclear ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_wcolor_set

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wcolor_setSets windows color pairings

Opis

int ncurses_wcolor_set ( resource $window , int $color_pair )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

color_pair



ncurses_werase

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_weraseErase window contents

Opis

int ncurses_werase ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_wgetch

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wgetchReads a character from keyboard (window)

Opis

int ncurses_wgetch ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_whline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_whlineDraws a horizontal line in a window at current position using an attributed character and max. n characters long

Opis

int ncurses_whline ( resource $window , int $charattr , int $n )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

charattr

n



ncurses_wmouse_trafo

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmouse_trafoTransforms window/stdscr coordinates

Opis

bool ncurses_wmouse_trafo ( resource $window , int &$y , int &$x , bool $toscreen )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

x

y

toscreen



ncurses_wmove

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wmoveMoves windows output position

Opis

int ncurses_wmove ( 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_wnoutrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wnoutrefreshCopies window to virtual screen

Opis

int ncurses_wnoutrefresh ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_wrefresh

(PHP 4 >= 4.2.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wrefreshRefresh window on terminal screen

Opis

int ncurses_wrefresh ( 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_wstandend

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandendEnd standout mode for a window

Opis

int ncurses_wstandend ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_wstandout

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wstandoutEnter standout mode for a window

Opis

int ncurses_wstandout ( resource $window )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window



ncurses_wvline

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL ncurses >= 1.0.0)

ncurses_wvlineDraws a vertical line in a window at current position using an attributed character and max. n characters long

Opis

int ncurses_wvline ( resource $window , int $charattr , int $n )
Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

window

charattr

n


Spis treści




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_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 , callable $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 ( callable $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




GNU Readline


Wstęp

Funkcje readline implementują interfejs do biblioteki GNU Readline. Pozwalają one na tworzenie edytowalnych wierszy poleceń. Jako przykład może posłużyć Bash, który pozwala na używanie klawiszy strzałek do poruszania się po wpisanej części polecenia lub przewijanie historii. Ze względu na interaktywność tej biblioteki, jest ona mało przydatna do pisania aplikacji sieciowych, lecz może być pomocna przy pisaniu skryptów przeznaczonych do używania PHP z wiersza poleceń.

Informacja: To rozszerzenie nie jest dostępne na platformie Windows.



Instalacja/Konfiguracja

Spis treści


Wymagania

Aby korzystać z funkcji readline niezbędne jest zainstalowanie biblioteki libreadline. Bibliotekę libreadline można znaleźć na witrynie projektu GNU Readline, » http://cnswww.cns.cwru.edu/~chet/readline/rltop.html Jest ona rozwijana przez Cheta Ramey'a, który jest także autorem Basha.

Z tych funkcji można skorzystać także przy użyciu biblioteki libedit, zamiennika biblioteki readline, wydanego na licencji innej niż GPL. Biblioteka libedit jest wydana na licencji BSD i można ją znaleźć pod adresem » http://www.thrysoee.dk/editline/.



Instalacja

Aby używać tych funkcji należy skompilować PHP w wersji CGI lub CLI z obsługą readline. Podczas konfiguracji PHP należy dodać opcję --with-readline[=DIR] . Aby używać odpowiednika readline - libedit, należy podczas konfiguracji PHP dodać opcję --with-libedit[=DIR] .



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Readline Opcje konfiguracyjne
Nazwa Domyślnie Możliwość zmian Rejestr zmian
cli.pager "" PHP_INI_ALL Available since PHP 5.4.0.
cli.prompt "\\b \\> " PHP_INI_ALL Available since PHP 5.4.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

cli.pager string

External tool to display output from command line.

cli.prompt string

Command line prompt.



Typy zasobów

To rozszerzenie nie posiada żadnych rodzajów zasobów.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



Funkcje Readline


readline_add_history

(PHP 4, PHP 5)

readline_add_historyDodaje wiersz do historii

Opis

bool readline_add_history ( string $wiersz )

Funkcja ta dodaje wiersz do historii wiersza poleceń.

Parametry

wiersz

Wiersz, który zostanie dodany do historii.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



readline_callback_handler_install

(PHP 5 >= 5.1.0)

readline_callback_handler_installInitializes the readline callback interface and terminal, prints the prompt and returns immediately

Opis

bool readline_callback_handler_install ( string $prompt , callable $callback )

Sets up a readline callback interface then prints prompt and immediately returns. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface.

The callback feature is useful when combined with stream_select() as it allows interleaving of IO and user input, unlike readline().

Parametry

prompt

The prompt message.

callback

The callback function takes one parameter; the user input returned.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Readline Callback Interface Example

<?php
function rl_callback($ret)
{
    global 
$c$prompting;

    echo 
"You entered: $ret\n";
    
$c++;

    if (
$c 10) {
        
$prompting false;
        
readline_callback_handler_remove();
    } else {
        
readline_callback_handler_install("[$c] Enter something: "'rl_callback');
    }
}

$c 1;
$prompting true;

readline_callback_handler_install("[$c] Enter something: "'rl_callback');

while (
$prompting) {
    
$w NULL;
    
$e NULL;
    
$n stream_select($r = array(STDIN), $w$enull);
    if (
$n && in_array(STDIN$r)) {
        
// read a character, will call the callback when a newline is entered
        
readline_callback_read_char();
    }
}

echo 
"Prompting disabled. All done.\n";
?>

Zobacz też:



readline_callback_handler_remove

(PHP 5 >= 5.1.0)

readline_callback_handler_removeRemoves a previously installed callback handler and restores terminal settings

Opis

bool readline_callback_handler_remove ( void )

Removes a previously installed callback handler and restores terminal settings.

Zwracane wartości

Returns TRUE if a previously installed callback handler was removed, or FALSE if one could not be found.

Przykłady

See readline_callback_handler_install() for an example of how to use the readline callback interface.

Zobacz też:



readline_callback_read_char

(PHP 5 >= 5.1.0)

readline_callback_read_charReads a character and informs the readline callback interface when a line is received

Opis

void readline_callback_read_char ( void )

Reads a character of user input. When a line is received, this function informs the readline callback interface installed using readline_callback_handler_install() that a line is ready for input.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

See readline_callback_handler_install() for an example of how to use the readline callback interface.

Zobacz też:



readline_clear_history

(PHP 4, PHP 5)

readline_clear_historyCzyści historię

Opis

bool readline_clear_history ( void )

Funkcja ta czyści całą historię wiersza poleceń.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



readline_completion_function

(PHP 4, PHP 5)

readline_completion_functionRejestruje funkcję dopełniania

Opis

bool readline_completion_function ( callback $funkcja )

Funkcja ta rejestruje funkcję dopełniania. Jest to efekt, który można zaobserwować wciskając klawisz TAB używając Basha.

Parametry

funkcja

Musisz podać nazwę istniejącej funkcji, która przyjmuje jako parametr częściowo wypełniony wiersz, i zwraca tablicę możliwych dopełnień.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



readline_info

(PHP 4, PHP 5)

readline_infoPobiera/ustawia różne wewnętrzne zmienne biblioteki readline

Opis

mixed readline_info ([ string $nazwa_zmiennej [, string $nowa_wartość ]] )

Pobiera lub ustawia różne wewnętrzne zmienne biblioteki readline.

Parametry

nazwa_zmiennej

Nazwa zmiennej.

nowa_wartość

Jeśli podana, to zostanie ustawiona nowa wartość.

Zwracane wartości

Jeśli funkcja zostanie wywołana bez parametrów, to zwrócona zostanie tablica z wartościami wszystkich ustawień biblioteki readline. Elementy tej tablicy będą miały takie indeksy: done, end, erase_empty_line, library_version, line_buffer, mark, pending_input, point, prompt, readline_name, i terminal_name.

Jeśli zostanie wywołana z jednym lub dwoma parametrami, zostanie zwrócona poprzenia wartość



readline_list_history

(PHP 4, PHP 5)

readline_list_historyZwraca historię wiersza poleceń

Opis

array readline_list_history ( void )

Pobiera całą historię wiersza poleceń.

Zwracane wartości

Funkcja ta zwraca tablicę zawierającą całą historię wiersza poleceń. Elementy są indeksowane przez liczby całkowite poczynając od zera.



readline_on_new_line

(PHP 5 >= 5.1.0)

readline_on_new_lineInform readline that the cursor has moved to a new line

Opis

void readline_on_new_line ( void )

Tells readline that the cursor has moved to a new line.

Zwracane wartości

Nie jest zwracana żadna wartość.



readline_read_history

(PHP 4, PHP 5)

readline_read_historyCzyta historię

Opis

bool readline_read_history ([ string $nazwa_pliku ] )

Funkcja ta czyta historię poleceń z pliku.

Parametry

nazwa_pliku

Ścieżka do pliku zawierającego historię poleceń.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



readline_redisplay

(PHP 5 >= 5.1.0)

readline_redisplayRedraws the display

Opis

void readline_redisplay ( void )

Redraws readline to redraw the display.

Zwracane wartości

Nie jest zwracana żadna wartość.



readline_write_history

(PHP 4, PHP 5)

readline_write_historyZapisuje historię

Opis

bool readline_write_history ([ string $nazwa_pliku ] )

Funkcja ta zapisuje historię poleceń do pliku.

Parametry

nazwa_pliku

Ścieżka zapisywanego pliku.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



readline

(PHP 4, PHP 5)

readlineCzyta linię

Opis

string readline ( string $prompt )

Funkcja ta zwraca pojedyńczy string pobrany od użytkownika. Jako parametr funkcji można podać string zawierający prompt (znak zachęty) który będzie wyświetlony. Zwracany string ma usunięty z końca znak nowego wiersza. Musisz dodać do linię do historii ręcznie używając readline_add_history().

Przykład #1 readline()

<?php
// pobierz 3 komendy od użytkownika
for ($i=0$i 3$i++) {
        
$line readline("Komenda: ");
        
readline_add_history($line);
}

// zrzuć historię
print_r(readline_list_history());

// zrzuć zmienne
print_r(readline_info());
?>

Spis treści





Rozszerzenia kompresji i archiwizacji


Bzip2


Wstęp

Funkcje bzip2 są używane do odczytu i zapisu skompresowanych plików bzip2 (.bz2).



Instalacja/Konfiguracja

Spis treści


Wymagania

Ten moduł używa funkcji z biblioteki » bzip2 stworzonej przez Juliana Seward'a. Moduł wymaga bzip2/libbzip2 w wersji >= 1.0.x.



Instalacja

Obsługa Bzip2 nie jest domyślnie włączona w PHP. Aby ją aktywować, należy użyć opcji konfiguracyjnej --with-bz2[=DIR] podczas kompilacji PHP z kodu źródłowego.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

To rozszeżenie definiuje jeden typ zasobów: wskaźnik pliku identyfikujący plik bz2, na którym pracuje.




Stałe predefiniowane

To rozszerzenie nie posiada żadnych stałych.



Przykłady

Ten przykład pokazuje otwiercie tymczasowego pliku i zapisu do niego łańcucha znaków. Następnie wyświetlana jest zawartość pliku.

Przykład #1 Przykład użycia bzip2

<?php

$filename 
"/tmp/testfile.bz2";
$str "To jest testowy lancuch znakow.\n";

// otwarcie pliku do zapisu
$bz bzopen($filename"w");

// zapisanie łańcucha znaków do pliku
bzwrite($bz$str);

// zamknięcie pliku
bzclose($bz);

// otwarcie pliku do odczytu
$bz bzopen($filename"r");

// przeczytanie 10 znaków
echo bzread($bz10);

// wyświetlaj dopóki nie nastąpi koniec pliku (lub następne 1024 znaki) i zamknij go.
echo bzread($bz);

bzclose($bz);

?>


Funkcje Bzip2


bzclose

(PHP 4 >= 4.0.4, PHP 5)

bzcloseZamyka otwarty plik bzip2

Opis

int bzclose ( resource $bz )

Funkcja zamyka wybrany uchwyt pliku bzip2.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • bzopen() - Otwiera skompresowany plik bzip2



bzcompress

(PHP 4 >= 4.0.4, PHP 5)

bzcompressCompress a string into bzip2 encoded data

Opis

mixed bzcompress ( string $source [, int $blocksize = 4 [, int $workfactor = 0 ]] )

bzcompress() compresses the given string and returns it as bzip2 encoded data.

Parametry

source

The string to compress.

blocksize

Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so.

workfactor

Controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case.

Regardless of the workfactor, the generated output is the same.

Zwracane wartości

The compressed string, or an error number if an error occurred.

Przykłady

Przykład #1 Compressing data

<?php
$str 
"sample data";
$bzstr bzcompress($str9);
echo 
$bzstr;
?>

Zobacz też:



bzdecompress

(PHP 4 >= 4.0.4, PHP 5)

bzdecompressDecompresses bzip2 encoded data

Opis

mixed bzdecompress ( string $source [, int $small = 0 ] )

bzdecompress() decompresses the given string containing bzip2 encoded data.

Parametry

source

The string to decompress.

small

If TRUE, an alternative decompression algorithm will be used which uses less memory (the maximum memory requirement drops to around 2300K) but works at roughly half the speed.

See the » bzip2 documentation for more information about this feature.

Zwracane wartości

The decompressed string, or an error number if an error occurred.

Przykłady

Przykład #1 Decompressing a String

<?php
$start_str 
"This is not an honest face?";
$bzstr bzcompress($start_str);

echo 
"Compressed String: ";
echo 
$bzstr;
echo 
"\n<br />\n";

$str bzdecompress($bzstr);
echo 
"Decompressed String: ";
echo 
$str;
echo 
"\n<br />\n";
?>

Zobacz też:



bzerrno

(PHP 4 >= 4.0.4, PHP 5)

bzerrnoZwraca numer błędu biblioteki bzip2.

Opis

int bzerrno ( resource $bz )

Zwraca numer dowolnego błędu bzip2 zwróconego przez podany wskaźnik pliku.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

Zwracane wartości

Zwraca numer błędu jako liczbę całkowitą.

Zobacz też:

  • bzerror() - Zwraca numer błędu bzip2 oraz opis błędu w postaci tablicy.
  • bzerrstr() - Zwraca opis błędu bzip2



bzerror

(PHP 4 >= 4.0.4, PHP 5)

bzerror Zwraca numer błędu bzip2 oraz opis błędu w postaci tablicy.

Opis

array bzerror ( resource $bz )

Zwraca tablicę asocjacyjną zawierającą opis i numer błędu biblioteki bzip2, który wystąpił podczas pracy z plikiem bz.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

Zwracane wartości

Zwraca tablicę asocjacyjną zawierającą, z kodem błedu w indeksie errno, i treścią błedu w indeksie errstr.

Przykłady

Przykład #1 bzerror() przykład

<?php
$error 
bzerror($bz);

echo 
$error["errno"];
echo 
$error["errstr"];
?>

Zobacz też:



bzerrstr

(PHP 4 >= 4.0.4, PHP 5)

bzerrstrZwraca opis błędu bzip2

Opis

string bzerrstr ( resource $bz )

Pobiera opis dowolnego błędu bzip2, który wystąpił podczas pracy z plikiem bz.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

Zwracane wartości

Zwraca łańcuch znaków zawierający opis błędu.

Zobacz też:

  • bzerrno() - Zwraca numer błędu biblioteki bzip2.
  • bzerror() - Zwraca numer błędu bzip2 oraz opis błędu w postaci tablicy.



bzflush

(PHP 4 >= 4.0.4, PHP 5)

bzflushWymusza zapisanie do pliku wszystkich danych z bufora

Opis

int bzflush ( resource $bz )

Wymusza zapisanie do pliku bz wszystkich danych znajdujących się w buforze.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Zobacz też:

  • bzread() - Binarnie bezpieczny odczyt pliku bzip2
  • bzwrite() - Binarnie bezpieczny zapis plików bzip2



bzopen

(PHP 4 >= 4.0.4, PHP 5)

bzopenOtwiera skompresowany plik bzip2

Opis

resource bzopen ( string $nazwa_pliku , string $tryb )

bzopen() otwiera plik bzip2 (.bz2) do odczytu lub zapisu.

Parametry

nazwa_pliku

Nazwa otwieranego pliku.

Tryb

Podobnie do funkcji fopen() obsługiwane są tylko 'r' (odczyt) i 'w' (zapis). Wszystko inne spowoduje, że bzopen zwróci FALSE.

Zwracane wartości

Jeśli otworzenie się nie powiedzie bzopen() zwróci FALSE, w przeciwnym wypadku zostanie zwrócony uchwyt do nowootwartego pliku.

Przykłady

Przykład #1 bzopen() przykład

<?php

$file 
"/tmp/foo.bz2";
$bz bzopen($file"r") or die("Nie mogę otworzyć do odczytu pliku: $file");

bzclose($bz);

?>

Zobacz też:



bzread

(PHP 4 >= 4.0.4, PHP 5)

bzreadBinarnie bezpieczny odczyt pliku bzip2

Opis

string bzread ( resource $bz [, int $długość = 1024 ] )

bzread() odczytuje z podanego wskaźnika pliku.

Odczytywanie jest zatrzymywane, gdy przeczytano długość (nieskompresowanych) bajtów lub osiągnięto EOF, cokolwiek wystąpi pierwsze.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

długość

Jeśli nie została określona bzread() zostaną odczytane 1024 (nieskompresowane) bajty. Maksymalnie może zostać odczytanych 8192 bajtów.

Zwracane wartości

Zwraca nieskompresowane dane lub FALSE w przypadku błędu.

Przykłady

Przykład #1 bzread() przykład

<?php

$file 
"/tmp/foo.bz2";
$bz bzopen($file"r") or die("Nie mogę otworzyć $file");

$decompressed_file '';
while (!
feof($bz)) {
  
$decompressed_file .= bzread($bz4096);
}
bzclose($bz);

echo 
"Zawartość pliku $file to: <br />\n";
echo 
$decompressed_file;

?>

Zobacz też:

  • bzwrite() - Binarnie bezpieczny zapis plików bzip2
  • feof() - Sprawdza czy wskaźnik pliku jest na końcu pliku (EOF)
  • bzopen() - Otwiera skompresowany plik bzip2



bzwrite

(PHP 4 >= 4.0.4, PHP 5)

bzwriteBinarnie bezpieczny zapis plików bzip2

Opis

int bzwrite ( resource $bz , string $dane [, int $długość ] )

bzwrite() zapisuje łaźcuch znaków do podanego strumienia pliku bzip2.

Parametry

bz

Uchwyt do pliku musi być poprawny oraz musi wskazywać na plik otwarty za pomocą funkcji bzopen().

dane

Zapisywane dane.

długość

Jeśłi podano, zapisywanie zostanie zakończone po zapisaniu długość (nieskompresowanych) bajtów lub po skończeniu się danych cokolwiek nastąpi wcześniej.

Zwracane wartości

Zwraca liczbę zapisanych bajtów, lub FALSE w przypadku błędu.

Przykłady

Przykład #1 bzwrite() przykład

<?php
$str 
"nieskompresowane dane";
$bz bzopen("/tmp/foo.bz2""w");
bzwrite($bz$strstrlen($str));
bzclose($bz);
?>

Zobacz też:

  • bzread() - Binarnie bezpieczny odczyt pliku bzip2
  • bzopen() - Otwiera skompresowany plik bzip2


Spis treści

  • bzclose — Zamyka otwarty plik bzip2
  • bzcompress — Compress a string into bzip2 encoded data
  • bzdecompress — Decompresses bzip2 encoded data
  • bzerrno — Zwraca numer błędu biblioteki bzip2.
  • bzerror — Zwraca numer błędu bzip2 oraz opis błędu w postaci tablicy.
  • bzerrstr — Zwraca opis błędu bzip2
  • bzflush — Wymusza zapisanie do pliku wszystkich danych z bufora
  • bzopen — Otwiera skompresowany plik bzip2
  • bzread — Binarnie bezpieczny odczyt pliku bzip2
  • bzwrite — Binarnie bezpieczny zapis plików bzip2



LZF


Wstęp

LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. It can be optimized for speed or space at the time of compilation. This extension is using » liblzf library by Marc Lehmann for its operations.



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/lzf.

In order to use these functions you must compile PHP with lzf support by using the --with-lzf[=DIR] configure option. You may also pass --enable-lzf-better-compression to optimize LZF for space rather than speed.

Windows users will enable php_lzf.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/



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.



LZF Funkcje


lzf_compress

(PECL lzf >= 0.1.0)

lzf_compress LZF compression

Opis

string lzf_compress ( string $data )

lzf_compress() compresses the given data string using LZF encoding.

Parametry

data

The string to compress.

Zwracane wartości

Returns the compressed data or FALSE if an error occurred.

Zobacz też:



lzf_decompress

(PECL lzf >= 0.1.0)

lzf_decompress LZF decompression

Opis

string lzf_decompress ( string $data )

lzf_compress() decompresses the given data string containing lzf encoded data.

Parametry

data

The compressed string.

Zwracane wartości

Returns the decompressed data or FALSE if an error occurred.

Zobacz też:



lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for Determines what LZF extension was optimized for

Opis

int lzf_optimized_for ( void )

Determines what was LZF extension optimized for during compilation.

Zwracane wartości

Returns 1 if LZF was optimized for speed, 0 for compression.


Spis treści




Phar


Wstęp

The phar extension provides a way to put entire PHP applications into a single file called a "phar" (PHP Archive) for easy distribution and installation. In addition to providing this service, the phar extension also provides a file-format abstraction method for creating and manipulating tar and zip files through the PharData class, much as PDO provides a unified interface for accessing different databases. Unlike PDO, which cannot convert between different databases, Phar also can convert between tar, zip and phar file formats with a single line of code. see Phar::convertToExecutable() for one example.

What is phar? Phar archives are best characterized as a convenient way to group several files into a single file. As such, a phar archive provides a way to distribute a complete PHP application in a single file and run it from that file without the need to extract it to disk. Additionally, phar archives can be executed by PHP as easily as any other file, both on the commandline and from a web server. Phar is kind of like a thumb drive for PHP applications.

Phar implements this functionality through a Stream Wrapper. Normally, to use an external file within a PHP script, you would use include()

Przykład #1 Using an external file

<?php
 
include '/path/to/external/file.php';
 
?>

PHP can be thought of as actually translating /path/to/external/file.php into a stream wrapper as file:///path/to/external/file.php, and under the hood it does in fact use the plain file stream wrapper stream functions to access all local files.

To use a file named file.php contained with a phar archive /path/to/myphar.phar, the syntax is very similar to the file:// syntax above.

Przykład #2 Using a file within a phar archive

<?php
 
include 'phar:///path/to/myphar.phar/file.php';
 
?>

In fact, one can treat a phar archive exactly as if it were an external disk, using any of fopen()-related functions, opendir() and mkdir()-related functions to read, change, or create new files and directories within the phar archive. This allows complete PHP applications to be distributed in a single file and run directly from that file.

The most common usage for a phar archive is to distribute a complete application in a single file. For instance, the PEAR Installer that is bundled with PHP versions is distributed as a phar archive. To use a phar archive distributed in this way, the archive can be executed on the command-line or via a web server.

Phar archives can be distributed as tar archives, zip archives, or as the custom phar file format designed specifically for the phar extension. Each file format has advantages and disadvantages. The tar and zip file formats can be read or extracted by any third-party tool that can read the format, but require the phar extension in order to run with PHP. The phar file format is customized and unique to the phar extension, and can only be created by the phar extension or the PEAR package » PHP_Archive, but has the advantage that applications created in this format will run even if the phar extension is not enabled.

In other words, even with the phar extension disabled, one can execute or include a phar-based archive. Accessing individual files within a phar archive is only possible with the phar extension unless the phar archive was created by PHP_Archive.

The phar extension is also capable of converting a phar archive from tar to zip or to phar file format in a single command:

Przykład #3 Converting a phar archive from phar to tar file format

<?php
 $phar 
= new Phar('myphar.phar');
 
$pgz $phar->convertToExecutable(Phar::TARPhar::GZ); // makes myphar.phar.tar.gz
 
?>

Phar can compress individual files or an entire archive using gzip compression or bzip2 compression, and can verify archive integrity automatically through the use of md5(), sha1(), sha256(), or sha512() signatures.

Lastly, the Phar extension is security-conscious, and disables write access to executable phar archives by default, and requires system-level disabling of the phar.readonly php.ini setting in order to create or modify phar archives. Normal tar and zip archives without an executable stub can always be created or modified using the PharData class.

If you are creating applications for distribution, you will want to read How to create Phar Archives. If you want more information on the differences between the three file formats that phar supports, you should read Phar, Tar and Zip.

If you are using phar applications, there are helpful tips in How to use Phar Archives

The word phar is a contraction of PHP and Archive and is based loosely on the jar (Java Archive) familiar to Java developers.

The implementation for Phar archives is based on the PEAR package » PHP_Archive, and the implementation details are similar, although the Phar extension is much more powerful. In addition, the Phar extension allows most PHP applications to be run unmodified while PHP_Archive-based phar archives often require extensive modification in order to work.



Instalacja/Konfiguracja

Spis treści


Wymagania

Phar requires PHP 5.2.0 or newer. Additional features require the SPL extension in order to take advantage of iteration and array access to a Phar's file contents. The phar stream does not require any additional extensions to function.

You may optionally wish to enable the zlib and bzip2 extensions to take advantage of compressed phar support. In addition, to take advantage of OpenSSL signing, the OpenSSL extension must be enabled.

Note that a bug in the zlib.deflate stream filter fixed in PHP version 5.2.6 and newer may cause truncation of gzip and bzip2-compressed phar archives.



Instalacja

The Phar extension is built into PHP as of PHP version 5.3.0. Phar may be installed via the PECL extension with previous PHP versions, and the » Phar PECL page contains further information and history.

Windows users must include the php_phar.dll file within php.ini to use this extension.



Konfiguracja wykonawcza

Na działanie tych funkcji wpływają ustawienia zawarte w pliku php.ini.

Filesystem and Streams Configuration Options
Nazwa Domyślnie Możliwość zmian Rejestr zmian
phar.readonly "1" PHP_INI_ALL  
phar.require_hash "1" PHP_INI_ALL  
phar.extract_list "" PHP_INI_ALL Available from phar 1.1.0 to 1.2.3, removed in 2.0.0.
phar.cache_list "" PHP_INI_SYSTEM Available from phar 2.0.0.

Oto krótkie wyjaśnienie dyrektyw konfiguracji.

phar.readonly boolean

This option disables creation or modification of Phar archives using the phar stream or Phar object's write support. This setting should always be enabled on production machines, as the phar extension's convenient write support could allow straightforward creation of a php-based virus when coupled with other common security vulnerabilities.

Informacja:

This setting can only be unset in php.ini due to security reasons. If phar.readonly is disabled in php.ini, the user may enable phar.readonly in a script or disable it later. If phar.readonly is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

phar.require_hash boolean

This option will force all opened Phar archives to contain some kind of signature (currently MD5, SHA1, SHA256 and SHA512 are supported), and will refuse to process any Phar archive that does not contain a signature.

Informacja:

This setting can only be unset in php.ini due to security reasons. If phar.require_hash is disabled in php.ini, the user may enable phar.require_hash in a script or disable it later. If phar.require_hash is enabled in php.ini, a script may harmlessly "re-enable" the INI variable, but may not disable it.

This setting does not affect reading plain tar files with the PharData class.

phar.extract_list string

This INI setting has been removed as of phar 2.0.0

Allows mappings from a full path to a phar archive or its alias to the location of its extracted files. The format of the parameter is name=archive,name2=archive2. This allows extraction of phar files to disk, and allows phar to act as a kind of mapper to extracted disk files. This is often done for performance reasons, or to assist with debugging a phar.

Przykład #1 phar.extract_list usage example

in php.ini:
phar.extract_list = archive=/full/path/to/archive/,arch2=/full/path/to/arch2
<?php
include "phar://archive/content.php";
include 
"phar://arch2/foo.php";
?>

phar.cache_list string

This INI setting was added in phar 2.0.0

Allows mapping phar archives to be pre-parsed at web server startup, providing a performance improvement that brings running files out of a phar archive very close to the speed of running those files from a traditional disk-based installation.

Przykład #2 phar.cache_list usage example

in php.ini (windows):
phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar
in php.ini (unix):
phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar



Typy zasobów

The Phar extension provides the phar stream, which allows accessing files contained within a phar transparently. See also the description of the Phar file format.




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.

Phar compression constants
Constant Value Description
Phar::NONE (integer) 0x00000000 no compression
Phar::COMPRESSED (integer) 0x0000F000 bitmask that can be used with file flags to determine if any compression is present
Phar::GZ (integer) 0x00001000 zlib (gzip) compression
Phar::BZ2 (integer) 0x00002000 bzip2 compression
Phar file format constants
Constant Value Description
Phar::SAME (integer) 0 retain the same file format
Phar::PHAR (integer) 1 phar file format
Phar::TAR (integer) 2 tar file format
Phar::ZIP (integer) 3 zip file format
Phar signature constants
Constant Value Description
Phar::MD5 (integer) 0x0001 signature with md5 hash algorithm
Phar::SHA1 (integer) 0x0002 signature with sha1 hash algorithm
Phar::SHA256 (integer) 0x0003 signature with sha256 hash algorithm (requires hash extension)
Phar::SHA512 (integer) 0x0004 signature with sha512 hash algorithm (requires hash extension)
Phar::OPENSSL (integer) 0x0010 signature with OpenSSL public/private key pair. This is a true, asymmetric key signature.
Phar webPhar mime override constants
Constant Value Description
Phar::PHP (integer) 1 used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file
Phar::PHPS (integer) 2 used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP source file through highlight_file()


Using Phar Archives

Spis treści


Using Phar Archives: Introduction

Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. A Phar archive application is used exactly like any other PHP application:

php coolapplication.phar
  

Using a Phar archive library is identical to using any other PHP library:

<?php
include 'coollibrary.phar';
?>

The phar stream wrapper provides the core of the phar extension, and is explained in detail here. The phar stream wrapper allows accessing the files within a phar archive using PHP's standard file functions fopen(), opendir(), and others that work on regular files. The phar stream wrapper supports all read/write operations on both files and directories.

<?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?>

The Phar class implements advanced functionality for accessing files and for creating phar archives. The Phar class is explained in detail here.

<?php
try {
    
// open an existing phar
    
$p = new Phar('coollibrary.phar'0);
    
// Phar extends SPL's DirectoryIterator class
    
foreach (new RecursiveIteratorIterator($p) as $file) {
        
// $file is a PharFileInfo class, and inherits from SplFileInfo
        
echo $file->getFileName() . "\n";
        echo 
file_get_contents($file->getPathName()) . "\n"// display contents;
    
}
    if (isset(
$p['internal/file.php'])) {
        
var_dump($p['internal/file.php']->getMetadata());
    }

    
// create a new phar - phar.readonly must be 0 in php.ini
    // phar.readonly is enabled by default for security reasons.
    // On production servers, Phars need never be created,
    // only executed.
    
if (Phar::canWrite()) {
        
$p = new Phar('newphar.tar.phar'0'newphar.tar.phar');
        
// make this a tar-based phar archive, compressed with gzip compression (.tar.gz)
        
$p $p->convertToExecutable(Phar::TARPhar::GZ);

        
// create transaction - nothing is written to newphar.phar
        // until stopBuffering() is called, although temporary storage is needed
        
$p->startBuffering();
        
// add all files in /path/to/project, saving in the phar with the prefix "project"
        
$p->buildFromIterator(new RecursiveIteratorIterator(new DirectoryIterator('/path/to/project')), '/path/to/');

        
// add a new file via the array access API
        
$p['file1.txt'] = 'Information';
        
$fp fopen('hugefile.dat''rb');
        
// copy all data from the stream
        
$p['data/hugefile.dat'] = $fp;

        if (
Phar::canCompress(Phar::GZ)) {
            
$p['data/hugefile.dat']->compress(Phar::GZ);
        }

        
$p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
        
// any value can be saved as file-specific meta-data
        
$p['images/wow.jpg']->setMetadata(array('mime-type' => 'image/jpeg'));
        
$p['index.php'] = file_get_contents('index.php');
        
$p->setMetadata(array('bootstrap' => 'index.php'));

        
// save the phar archive to disk
        
$p->stopBuffering();
    }
} catch (
Exception $e) {
    echo 
'Could not open Phar: '$e;
}
?>

In addition, verification of phar file contents can be done using any of the supported symmetric hash algorithms (MD5, SHA1, SHA256 and SHA512 if ext/hash is enabled) and using asymmetric public/private key signing using OpenSSL (new in Phar 2.0.0). To take advantage of OpenSSL signing, you need to generate a public/private key pair, and use the private key to set the signature using Phar::setSignatureAlgorithm(). In addition, the public key as extracted using this code:

<?php
$public 
openssl_get_publickey(file_get_contents('private.pem'));
$pkey '';
openssl_pkey_export($public$pkey);
?>
must be saved adjacent to the phar archive it verifies. If the phar archive is saved as /path/to/my.phar, the public key must be saved as /path/to/my.phar.pubkey, or phar will be unable to verify the OpenSSL signature.

As of version 2.0.0, The Phar class also provides 3 static methods, Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that are crucial to packaging up PHP applications designed for usage on regular filesystems and for web-based applications. Phar::webPhar() implements a front controller that routes HTTP calls to the correct location within the phar archive. Phar::mungServer() is used to modify the values of the $_SERVER array to trick applications that process these values. Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(), file_get_contents(), opendir(), and all of the stat-based functions (file_exists(), is_readable() and so on) and route all relative paths to locations within the phar archive.

As an example, packaging up a release of the popular phpMyAdmin application for use as a phar archive requires only this simple script and then phpMyAdmin.phar.tar.php can be accessed as a regular file from your web server after modifying the user/password:

<?php
@unlink('phpMyAdmin.phar.tar.php');
copy('phpMyAdmin-2.11.3-english.tar.gz''phpMyAdmin.phar.tar.php');
$a = new Phar('phpMyAdmin.phar.tar.php');
$a->startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = '<?php
/* Servers configuration */
$i = 0;

/* Server localhost (config:root) [1] */
$i++;
$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';
$cfg[\'Servers\'][$i][\'extension\'] = \'mysqli\';
$cfg[\'Servers\'][$i][\'connect_type\'] = \'tcp\';
$cfg[\'Servers\'][$i][\'compress\'] = false;
$cfg[\'Servers\'][$i][\'auth_type\'] = \'config\';
$cfg[\'Servers\'][$i][\'user\'] = \'root\';
$cfg[\'Servers\'][$i][\'password\'] = \'\';


/* End of servers configuration */
if (strpos(PHP_OS, \'WIN\') !== false) {
    $cfg[\'UploadDir\'] = getcwd();
} else {
    $cfg[\'UploadDir\'] = \'/tmp/pharphpmyadmin\';
    @mkdir(\'/tmp/pharphpmyadmin\');
    @chmod(\'/tmp/pharphpmyadmin\', 0777);
}'
;
$a->setStub('<?php
Phar::interceptFileFuncs();
Phar::webPhar("phpMyAdmin.phar", "phpMyAdmin-2.11.3-english/index.php");
echo "phpMyAdmin is intended to be executed from a web browser\n";
exit -1;
__HALT_COMPILER();
'
);
$a->stopBuffering();
?>



Using Phar Archives: the phar stream wrapper

The Phar stream wrapper fully supports fopen() for read and write (not append), unlink(), stat(), fstat(), fseek(), rename() and directory stream operations opendir() and as of version 2.0.0, rmdir() and mkdir().

Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:

<?php
$context 
stream_context_create(array('phar' =>
                                    array(
'compress' => Phar::GZ)),
                                    array(
'metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php'0$context);
?>

The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.

Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read-only operations.



Using Phar Archives: the Phar and PharData class

The Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array.

The PharData class extends the Phar, and allows creating and modifying non-executable (data) tar and zip archives even if phar.readonly=1 in php.ini. As such, PharData::setAlias() and PharData::setStub() are both disabled as the concept of alias and stub are unique to executable phar archives.

It is important to note that when creating a Phar archive, the full path should be passed to the Phar object constructor. Relative paths will fail to initialize.

Assuming that $p is a Phar object initialized as follows:

<?php
$p 
= new Phar('/path/to/myphar.phar'0'myphar.phar');
?>

An empty Phar archive will be created at /path/to/myphar.phar, or if /path/to/myphar.phar already exists, it will be opened again. The literal myphar.phar demonstrates the concept of an alias that can be used to reference /path/to/myphar.phar in URLs as in:

<?php
// these two calls to file_get_contents() are equivalent if
// /path/to/myphar.phar has an explicit alias of "myphar.phar"
// in its manifest, or if the phar was initialized with the
// previous example's Phar object setup
$f file_get_contents('phar:///path/to/myphar.phar/whatever.txt');
$f file_get_contents('phar://myphar.phar/whatever.txt');
?>

With the newly created $p Phar object, the following is possible:

  • $a = $p['file.php'] creates a PharFileInfo class that refers to the contents of phar://myphar.phar/file.php
  • $p['file.php'] = $v creates a new file (phar://myphar.phar/file.php), or overwrites an existing file within myphar.phar. $v can be either a string or an open file pointer, in which case the entire contents of the file will be used to create the new file. Note that $p->addFromString('file.php', $v) is functionally equivalent to the above. Also possible is to add the contents of a file with $p->addFile('/path/to/file.php', 'file.php'). Lastly, an empty directory can be created with $p->addEmptyDir('empty').
  • isset($p['file.php']) can be used to determine whether phar://myphar.phar/file.php exists within myphar.phar.
  • unset($p['file.php']) erases phar://myphar.phar/file.php from myphar.phar.

In addition, the Phar object is the only way to access Phar-specific metadata, through Phar::getMetadata(), and the only way to set or retrieve a Phar archive's PHP loader stub through Phar::getStub() and Phar::setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class.

The full list of Phar object functionality is documented below.

The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata.




Creating Phar Archives

Spis treści


Creating Phar Archives: Introduction

To be written fully in the near future. Before reading this, be sure to read How to use Phar Archives.

A great place to start is by reading about Phar::buildFromIterator(), and the specifics of the file format choices available for archives. A healthy understanding of what a stub is and does is crucial to phar archive creation, and so Phar::setStub() and Phar::createDefaultStub() are good places to start as well. If you are distributing a web-based application, it is crucial to know about Phar::webPhar() and related method Phar::mungServer(). Any application that accesses its own files should also consider using Phar::interceptFileFuncs().




What makes a phar a phar and not a tar or a zip?

Spis treści


Ingredients of all Phar archives, independent of file format

All Phar archives contain three to four sections:

  1. a stub

  2. a manifest describing the contents

  3. the file contents

  4. [optional] a signature for verifying Phar integrity (phar file format only)



Phar file stub

A Phar's stub is a simple PHP file. The smallest possible stub follows:

<?php __HALT_COMPILER();

A stub must contain as a minimum, the __HALT_COMPILER(); token at its conclusion. Typically, a stub will contain loader functionality like so:

<?php
Phar
::mapPhar();
include 
'phar://myphar.phar/index.php';
__HALT_COMPILER();

There are no restrictions on the contents of a Phar stub, except for the requirement that it conclude with __HALT_COMPILER();. The closing PHP tag

?>
may be included or omitted, but there can be no more than 1 space between the ; and the close tag
?>
or the phar extension will be unable to process the Phar archive's manifest.

In a tar or zip-based phar archive, the stub is stored in the .phar/stub.php file. The default stub for phar-based Phar archives contains approximately 7k of code to extract the contents of the phar and execute them. See Phar::createDefaultStub() for more detail.

The phar alias is stored in a tar or zip-based phar archive in the .phar/alias.txt file as plain text.



Head-to-head comparison of Phar, Tar and Zip

What are the good and the bad things about the three supported file formats in the phar extension? This table attempts to address that question.

Feature matrix: Phar vs. Tar vs. Zip
Feature Phar Tar Zip
Standard File Format No Yes Yes
Can be executed without the Phar Extension [1] Yes No No
Per-file compression Yes No Yes
Whole-archive compression Yes Yes No
Whole-archive signature validation Yes Yes Yes (PHP 5.3.1+)
Web-specific application support Yes Yes Yes
Per-file Meta-data Yes Yes Yes
Whole-Archive Meta-data Yes Yes Yes
Archive creation/modification [2] Yes Yes Yes
Full support for all stream wrapper functions Yes Yes Yes
Can be created/modified even if phar.readonly=1 [3] No Yes Yes

Wskazówka

[1] PHP can only directly access the contents of a Phar archive without the Phar extension if it is using a stub that extracts the contents of the phar archive. The stub created by Phar::createDefaultStub() extracts the phar archive and runs its contents from a temporary directory if no phar extension is found.

Wskazówka

[2] All write access requires phar.readonly to be disabled in php.ini or on the command-line directly.

Wskazówka

[3] Only tar and zip archives without .phar in their filename and without an executable stub .phar/stub.php can be created if phar.readonly=1.



Tar-based phars

Archives based on the tar file format follow the more modern USTAR file format. The design of the tar file header makes them more efficient to access than the zip file format, and almost as efficient as the phar file format. File names are limited to 255 bytes, including full path within the phar archive. There is no limit on the number of files within a tar-based phar archive. These archives can fully compressed in gzip or bzip2 format and still be executed by the Phar extension.

To compress an entire archive, use Phar::compress(). To decompress an entire archive, use Phar::decompress().



Zip-based phars

Archives based on the zip file format support several features built into the zip file format. Per-file and whole-archive metadata is stored in the zip file comment and zip archive comment as a serialized string. Pre-existing zip comments will be successfully read as a string. Per-file compression read/write is supported with zlib compression, and read access is supported with bzip2 compression. There is no limit on the number of files within a zip-based phar archive. Empty directories are stored in the zip archive as files with a trailing slash like my/directory/



Phar File Format

The phar file format is literally laid out as stub/manifest/contents/signature, and stores the crucial information of what is included in the phar archive in its manifest.

The Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as file user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order.

All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files.

The basic file format of a Phar archive manifest is as follows:

Global Phar manifest format
Size in bytes Description
4 bytes Length of manifest in bytes (1 MB limit)
4 bytes Number of files in the Phar
2 bytes API version of the Phar manifest (currently 1.0.0)
4 bytes Global Phar bitmapped flags
4 bytes Length of Phar alias
?? Phar alias (length based on previous)
4 bytes Length of Phar metadata (0 for none)
?? Serialized Phar Meta-data, stored in serialize() format
at least 24 * number of entries bytes entries for each file



Global Phar bitmapped flags

Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:

Bitmap values recognized
Value Description
0x00010000 If set, this Phar contains a verification signature
0x00001000 If set, this Phar contains at least 1 file that is compressed with zlib compression
0x00002000 If set, this Phar contains at least 1 file that is compressed with bzip compression



Phar manifest file entry definition

Each file in the manifest contains the following information:

Phar Manifest file entry
Size in bytes Description
4 bytes Filename length in bytes
?? Filename (length specified in previous)
4 bytes Un-compressed file size in bytes
4 bytes Unix timestamp of file
4 bytes Compressed file size in bytes
4 bytes CRC32 checksum of un-compressed file contents
4 bytes Bit-mapped File-specific flags
4 bytes Serialized File Meta-data length (0 for none)
?? Serialized File Meta-data, stored in serialize() format

Note that as of API version 1.1.1, empty directories are stored as filenames with a trailing slash like my/directory/

The File-specific bitmap values recognized are:

Bitmap values recognized
Value Description
0x000001FF These bits are reserved for defining specific file permissions of a file. Permissions are used for fstat() and can be used to recreate desired permissions upon extraction.
0x00001000 If set, this file is compressed with zlib compression
0x00002000 If set, this file is compressed with bzip compression



Phar Signature format

Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The two signature formats supported at this time are MD5 and SHA1.

Signature format
Length in bytes Description
16 or 20 bytes The actual signature, 20 bytes for an SHA1 signature, 16 bytes for an MD5 signature, 32 bytes for an SHA256 signature, and 64 bytes for an SHA512 signature.
4 bytes Signature flags. 0x0001 is used to define an MD5 signature, 0x0002 is used to define an SHA1 signature, 0x0004 is used to define an SHA256 signature, and 0x0008 is used to define an SHA512 signature. The SHA256 and SHA512 signature support was introduced with API version 1.1.0.
4 bytes Magic GBMB used to define the presence of a signature.




The Phar class

(No version information available, might only be in SVN)

Wstęp

The Phar class provides a high-level interface to accessing and creating phar archives.

Krótki opis klasy

Phar extends RecursiveDirectoryIterator implements Countable , ArrayAccess {
/* Właściwości */
/* Metody */
void addEmptyDir ( string $dirname )
void addFile ( string $file [, string $localname ] )
void addFromString ( string $localname , string $contents )
string apiVersion ( void )
array buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool canCompress ([ int $type = 0 ] )
bool canWrite ( void )
object compress ( int $compression [, string $extension ] )
bool compressAllFilesBZIP2 ( void )
bool compressAllFilesGZ ( void )
void compressFiles ( int $compression )
__construct ( string $fname [, int $flags [, string $alias ]] )
PharData convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
Phar convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
int count ( void )
string createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
mixed getMetadata ( void )
bool getModified ( void )
array getSignature ( void )
string getStub ( void )
array getSupportedCompression ( void )
array getSupportedSignatures ( void )
string getVersion ( void )
bool hasMetadata ( void )
void interceptFileFuncs ( void )
bool isBuffering ( void )
mixed isCompressed ( void )
bool isFileFormat ( int $format )
bool isValidPharFilename ( string $filename [, bool $executable = true ] )
bool isWritable ( void )
bool loadPhar ( string $filename [, string $alias ] )
bool mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void mount ( string $pharpath , string $externalpath )
void mungServer ( array $munglist )
bool offsetExists ( string $offset )
int offsetGet ( string $offset )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
string running ([ bool $retphar = true ] )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
void setMetadata ( mixed $metadata )
void setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool setStub ( string $stub )
void startBuffering ( void )
void stopBuffering ( void )
bool uncompressAllFiles ( void )
bool unlinkArchive ( string $archive )
void webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
}

Phar::addEmptyDir

(Unknown)

Phar::addEmptyDirAdd an empty directory to the phar archive

Opis

void Phar::addEmptyDir ( string $dirname )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parametry

dirname

The name of the empty directory to create in the phar archive

Zwracane wartości

no return value, exception is thrown on failure.

Przykłady

Przykład #1 A Phar::addEmptyDir() example

<?php
try {
    
$a = new Phar('/path/to/phar.phar');

    
$a->addEmptyDir('/full/path/to/file');
    
// demonstrates how this file is stored
    
$b $a['full/path/to/file']->isDir();
} catch (
Exception $e) {
    
// handle errors here
}
?>

Zobacz też:



Phar::addFile

(Unknown)

Phar::addFileAdd a file from the filesystem to the phar archive

Opis

void Phar::addFile ( string $file [, string $localname ] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

With this method, any file or URL can be added to the phar archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parametry

file

Full or relative path to a file on disk to be added to the phar archive.

localname

Path that the file will be stored in the archive.

Zwracane wartości

no return value, exception is thrown on failure.

Przykłady

Przykład #1 A Phar::addFile() example

<?php
try {
    
$a = new Phar('/path/to/phar.phar');

    
$a->addFile('/full/path/to/file');
    
// demonstrates how this file is stored
    
$b $a['full/path/to/file']->getContent();

    
$a->addFile('/full/path/to/file''my/file.txt');
    
$c $a['my/file.txt']->getContent();

    
// demonstrate URL usage
    
$a->addFile('http://www.example.com''example.html');
} catch (
Exception $e) {
    
// handle errors here
}
?>

Zobacz też:



Phar::addFromString

(Unknown)

Phar::addFromStringAdd a file from the filesystem to the phar archive

Opis

void Phar::addFromString ( string $localname , string $contents )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

With this method, any string can be added to the phar archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

Parametry

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Zwracane wartości

no return value, exception is thrown on failure.

Przykłady

Przykład #1 A Phar::addFromString() example

<?php
try {
    
$a = new Phar('/path/to/phar.phar');

    
$a->addFromString('path/to/file.txt''my simple file');
    
$b $a['path/to/file.txt']->getContent();

    
// to add contents from a stream handle for large files, use offsetSet()
    
$c fopen('/path/to/hugefile.bin');
    
$a['largefile.bin'] = $c;
    
fclose($c);
} catch (
Exception $e) {
    
// handle errors here
}
?>

Zobacz też:



Phar::apiVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::apiVersionReturns the api version

Opis

string Phar::apiVersion ( void )

Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API version 1.1.1 is required to store empty directories.

Parametry

Zwracane wartości

The API version string as in "1.0.0".

Przykłady

Przykład #1 A Phar::apiVersion() example

<?php
echo Phar::apiVersion();
?>

Powyższy przykład wyświetli:

1.1.1



Phar::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromDirectoryConstruct a phar archive from the files within a directory.

Opis

array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Populate a phar archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use Phar::buildFromIterator().

Parametry

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

Zwracane wartości

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Błędy/Wyjątki

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Przykłady

Przykład #1 A Phar::buildFromDirectory() example

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar'0'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php''www/index.php'));

$phar2 = new Phar('project2.phar'0'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project''/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php''www/index.php'));
?>

Zobacz też:



Phar::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::buildFromIteratorConstruct a phar archive from an iterator.

Opis

array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

Parametry

iter

Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

base_directory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive

Zwracane wartości

Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Przykłady

Przykład #1 A Phar::buildFromIterator() with SplFileInfo

For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.phar" phar archive:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar'0'project.phar');
$phar->buildFromIterator(
    new 
RecursiveIteratorIterator(
     new 
RecursiveDirectoryIterator('/path/to/project')),
    
'/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php''www/index.php'));
?>

The file project.phar can then be used immediately. Phar::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the phar archive.

As an interesting note, Phar::buildFromIterator() can also be used to copy the contents of an existing phar archive, as the Phar object descends from DirectoryIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar'0'project.phar');
$phar->buildFromIterator(
    new 
RecursiveIteratorIterator(
     new 
Phar('/path/to/anotherphar.phar')),
    
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php''www/index.php'));
?>

Przykład #2 A Phar::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar'0'project.phar');
$phar->buildFromIterator(
    new 
ArrayIterator(
     array(
        
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        
'another/file.jpg' => fopen('/path/to/bigfile.jpg''rb'),
     )));
$phar->setStub($phar->createDefaultStub('cli/index.php''www/index.php'));
?>

Błędy/Wyjątki

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

Zobacz też:



Phar::canCompress

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canCompressReturns whether phar extension supports compression using either zlib or bzip2

Opis

bool Phar::canCompress ([ int $type = 0 ] )

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

Parametry

type

Either Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

Zwracane wartości

TRUE if compression/decompression is available, FALSE if not.

Przykłady

Przykład #1 A Phar::canCompress() example

<?php
if (Phar::canCompress()) {
    echo 
file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
    echo 
'no compression available';
}
?>

Zobacz też:



Phar::canWrite

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::canWriteReturns whether phar extension supports writing and creating phars

Opis

bool Phar::canWrite ( void )

This static method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.

Parametry

Zwracane wartości

TRUE if write access is enabled, FALSE if it is disabled.

Przykłady

Przykład #1 A Phar::canWrite() example

<?php
if (Phar::canWrite()) {
    
file_put_contents('phar://myphar.phar/file.txt''hi there');
}
?>

Zobacz też:



Phar::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compressCompresses the entire Phar archive using Gzip or Bzip2 compression

Opis

object Phar::compress ( int $compression [, string $extension ] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

For tar-based and phar-based phar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

Parametry

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .phar.gz or .phar.bz2 for compressing phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing tar archives. For decompressing, the default file extensions are .phar and .phar.tar.

Zwracane wartości

Returns a Phar object.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Przykłady

Przykład #1 A Phar::compress() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

Zobacz też:



Phar::compressAllFilesBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesBZIP2Compresses all files in the current Phar archive using Bzip2 compression

Opis

bool Phar::compressAllFilesBZIP2 ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: Phar::compress(), Phar::decompress(), Phar::compressFiles() i Phar::decompressFiles().

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This method compresses all files in the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files prior to re-compressing with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not available, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Przykłady

Przykład #1 A Phar::compressAllFilesBZIP2() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressedBZIP2());
    
var_dump($file->isCompressedGZ());
}
$p->compressAllFilesBZIP2();
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressedBZIP2());
    
var_dump($file->isCompressedGZ());
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(true)
bool(false)
string(11) "myfile2.txt"
bool(true)
bool(true)
bool(false)

Zobacz też:



Phar::compressAllFilesGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::compressAllFilesGZCompresses all files in the current Phar archive using Gzip compression

Opis

bool Phar::compressAllFilesGZ ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: Phar::compress(), Phar::decompress(), Phar::compressFiles() i Phar::decompressFiles().

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

For tar-based phar archives, this method compresses the entire archive using gzip compression. The resulting file can be processed with the gunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the files prior to re-compressing with gzip compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Przykłady

Przykład #1 A Phar::compressAllFilesGZ() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressedBZIP2());
    
var_dump($file->isCompressedGZ());
}
$p->compressAllFilesGZ();
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressedBZIP2());
    
var_dump($file->isCompressedGZ());
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)

Zobacz też:



Phar::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::compressFilesCompresses all files in the current Phar archive

Opis

void Phar::compressFiles ( int $compression )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Parametry

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Przykłady

Przykład #1 A Phar::compressFiles() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

Zobacz też:



Phar::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::__constructConstruct a Phar archive object

Opis

Phar::__construct ( string $fname [, int $flags [, string $alias ]] )

Parametry

fname

Path to an existing Phar archive or to-be-created archive

flags

Flags to pass to parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

Błędy/Wyjątki

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

Przykłady

Przykład #1 A Phar::__construct() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'CURRENT_AS_FILEINFO KEY_AS_FILENAME,
                  
'my.phar');
} catch (
UnexpectedValueException $e) {
    die(
'Could not open my.phar');
} catch (
BadMethodCallException $e) {
    echo 
'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>



Phar::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToDataConvert a phar archive to a non-executable tar or zip file

Opis

PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive.

If no changes are specified, this method throws a BadMethodCallException if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parametry

format

This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

Zwracane wartości

The method returns a PharData object on success and throws an exception on failure.

Błędy/Wyjątki

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

Przykłady

Przykład #1 A Phar::convertToData() example

Using Phar::convertToData():

<?php
try {
    
$tarphar = new Phar('myphar.phar.tar');
    
// note that myphar.phar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.tar
    
$tar $tarphar->convertToData();
    
// convert to non-executable zip format, creates myphar.zip
    
$zip $tarphar->convertToData(Phar::ZIP);
    
// create myphar.tbz
    
$tgz $tarphar->convertToData(Phar::TARPhar::BZ2'.tbz');
    
// creates myphar.phar.tgz
    
$phar $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    
// handle the error here
}
?>

Zobacz też:



Phar::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::convertToExecutableConvert a phar archive to another executable phar archive file format

Opis

Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parametry

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

Zwracane wartości

The method returns a Phar object on success and throws an exception on failure.

Błędy/Wyjątki

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

Przykłady

Przykład #1 A Phar::convertToExecutable() example

Using Phar::convertToExecutable():

<?php
try {
    
$tarphar = new Phar('myphar.phar.tar');
    
// convert it to the phar file format
    // note that myphar.phar.tar is *not* unlinked
    
$phar $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    
$phar->setStub($phar->createDefaultStub('cli.php''web/index.php'));
    
// creates myphar.phar.tgz
    
$compressed $phar->convertToExecutable(Phar::TARPhar::GZ'.phar.tgz');
} catch (
Exception $e) {
    
// handle the error here
}
?>

Zobacz też:



Phar::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::copyCopy a file internal to the phar archive to another new file within the phar

Opis

bool Phar::copy ( string $oldfile , string $newfile )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using copy() with the phar stream wrapper.

Parametry

oldfile

newfile

Zwracane wartości

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

Błędy/Wyjątki

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

Przykłady

Przykład #1 A Phar::copy() example

This example shows using Phar::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
    
$phar = new Phar('myphar.phar');
    
$phar['a'] = 'hi';
    
$phar->copy('a''b');
    echo 
$phar['b']; // outputs "hi"
} catch (Exception $e) {
    
// handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a''phar//myphar.phar/c');
echo 
file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>



Phar::count

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::countReturns the number of entries (files) in the Phar archive

Opis

int Phar::count ( void )

Parametry

Zwracane wartości

The number of files contained within this phar, or 0 (the number zero) if none.

Przykłady

Przykład #1 A Phar::count() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
} catch (
Exception $e) {
    echo 
'Could not create phar:'$e;
}
echo 
'The new phar has ' $p->count() . " entries\n";
$p['file.txt'] = 'hi';
echo 
'The new phar has ' $p->count() . " entries\n";
?>

Powyższy przykład wyświetli:

The new phar has 0 entries
The new phar has 1 entries



Phar::createDefaultStub

(Unknown)

Phar::createDefaultStubCreate a phar-file format specific stub

Opis

string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )

This method is intended for creation of phar-file format-specific stubs, and is not intended for use with tar- or zip-based phar archives.

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>
or by simple execution:
php myphar.phar
    

This method provides a simple and easy method to create a stub that will run a startup file from the phar archive. In addition, different files can be specified for running the phar archive from the command line versus through a web server. The loader stub also calls Phar::interceptFileFuncs() to allow easy bundling of a PHP application that accesses the file system. If the phar extension is not present, the loader stub will extract the phar archive to a temporary directory and then operate on the files. A shutdown function erases the temporary files on exit.

Zwracane wartości

Returns a string containing the contents of a customized bootstrap loader (stub) that allows the created Phar archive to work with or without the Phar extension enabled.

Błędy/Wyjątki

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

Przykłady

Przykład #1 A Phar::createDefaultStub() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
$phar->setStub($phar->createDefaultStub('cli.php''web/index.php'));
} catch (
Exception $e) {
    
// handle errors
}
?>

Zobacz też:

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive



Phar::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompressDecompresses the entire Phar archive

Opis

object Phar::decompress ([ string $extension ] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

For tar-based and phar-based phar archives, this method decompresses the entire archive.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically changes the file extension of the archive, .phar by default for phar archives, or .phar.tar for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter.

Parametry

extension

For decompressing, the default file extensions are .phar and .phar.tar. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain .phar in their filename.

Zwracane wartości

A Phar object is returned.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

Przykłady

Przykład #1 A Phar::decompress() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 $p2->decompress(); // creates /path/to/my.phar
?>

Zobacz też:



Phar::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::decompressFilesDecompresses all files in the current Phar archive

Opis

bool Phar::decompressFiles ( void )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Przykłady

Przykład #1 A Phar::decompressFiles() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

Zobacz też:



Phar::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::delMetadataDeletes the global metadata of the phar

Opis

bool Phar::delMetadata ( void )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Deletes the global metadata of the phar

Parametry

Zwracane wartości

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Błędy/Wyjątki

Throws PharException if errors occur while flushing changes to disk.

Przykłady

Przykład #1 A Phar::delMetaData() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
var_dump($phar->getMetadata());
    
$phar->setMetadata("hi there");
    
var_dump($phar->getMetadata());
    
$phar->delMetadata();
    
var_dump($phar->getMetadata());
} catch (
Exception $e) {
    
// handle errors
}
?>

Powyższy przykład wyświetli:

NULL
string(8) "hi there"
NULL

Zobacz też:



Phar::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::deleteDelete a file within a phar archive

Opis

bool Phar::delete ( string $entry )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

Parametry

entry

Path within an archive to the file to delete.

Zwracane wartości

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Błędy/Wyjątki

Throws PharException if errors occur while flushing changes to disk.

Przykłady

Przykład #1 A Phar::delete() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
$phar->delete('unlink/me.php');
    
// this is equivalent to:
    
unlink('phar://myphar.phar/unlink/me.php');
} catch (
Exception $e) {
    
// handle errors
}
?>

Zobacz też:



Phar::extractTo

(Unknown)

Phar::extractToExtract the contents of a phar archive to a directory

Opis

bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Extract all files within a phar archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

Parametry

pathto

Path within an archive to the file to delete.

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to TRUE to enable overwriting existing files

Zwracane wartości

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Błędy/Wyjątki

Throws PharException if errors occur while flushing changes to disk.

Przykłady

Przykład #1 A Phar::extractTo() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
$phar->extractTo('/full/path'); // extract all files
    
$phar->extractTo('/another/path''file.txt'); // extract only file.txt
    
$phar->extractTo('/this/path',
        array(
'file1.txt''file2.txt')); // extract 2 files only
    
$phar->extractTo('/third/path'nulltrue); // extract all files, and overwrite
} catch (Exception $e) {
    
// handle errors
}
?>

Zobacz też:



Phar::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getMetadataReturns phar archive meta-data

Opis

mixed Phar::getMetadata ( void )

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

Parametry

No parameters.

Zwracane wartości

any PHP variable that can be serialized and is stored as meta-data for the Phar archive, or NULL if no meta-data is stored.

Przykłady

Przykład #1 A Phar::getMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
    
$p['file.php'] = '<?php echo "hello";';
    
$p->setMetadata(array('bootstrap' => 'file.php'));
    
var_dump($p->getMetadata());
} catch (
Exception $e) {
    echo 
'Could not modify phar:'$e;
}
?>

Powyższy przykład wyświetli:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

Zobacz też:



Phar::getModified

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getModifiedReturn whether phar was modified

Opis

bool Phar::getModified ( void )

This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.

Parametry

No parameters.

Zwracane wartości

TRUE if the phar has been modified since opened, FALSE if not.



Phar::getSignature

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getSignatureReturn MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Opis

array Phar::getSignature ( void )

Returns the verification signature of a phar archive in a hexadecimal string.

Parametry

Zwracane wartości

Array with the opened archive's signature in hash key and MD5, SHA-1, SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all executable phar archives if the phar.require_hash INI variable is set to true.



Phar::getStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getStubReturn the PHP loader or bootstrap stub of a Phar archive

Opis

string Phar::getStub ( void )

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>
or by simple execution:
php myphar.phar
    

Zwracane wartości

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

Błędy/Wyjątki

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

Przykłady

Przykład #1 A Phar::getStub() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
echo 
$p->getStub();
echo 
"==NEXT==\n";
$p->setStub("<?php
function __autoload(
$class)
{
    include 'phar://' . str_replace('_', '/', 
$class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>"
);
echo 
$p->getStub();
?>

Powyższy przykład wyświetli:

<?php __HALT_COMPILER(); ?>
==NEXT==
<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>

Zobacz też:



Phar::getSupportedCompression

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::getSupportedCompressionReturn array of supported compression algorithms

Opis

array Phar::getSupportedCompression ( void )

Parametry

No parameters.

Zwracane wartości

Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.

Zobacz też:



Phar::getSupportedSignatures

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::getSupportedSignaturesReturn array of supported signature types

Opis

array Phar::getSupportedSignatures ( void )

Return array of supported signature types

Parametry

No parameters.

Zwracane wartości

Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.

Zobacz też:



Phar::getVersion

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::getVersionReturn version info of Phar archive

Opis

string Phar::getVersion ( void )

Returns the API version of an opened Phar archive.

Parametry

Zwracane wartości

The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.

Zobacz też:



Phar::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::hasMetadataReturns whether phar has global meta-data

Opis

bool Phar::hasMetadata ( void )

Returns whether phar has global meta-data set.

Parametry

No parameters.

Zwracane wartości

Returns TRUE if meta-data has been set, and FALSE if not.

Przykłady

Przykład #1 A Phar::hasMetadata() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
var_dump($phar->hasMetadata());
    
$phar->setMetadata(array('thing' => 'hi'));
    
var_dump($phar->hasMetadata());
    
$phar->delMetadata();
    
var_dump($phar->hasMetadata());
} catch (
Exception $e) {
    
// handle error
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)
bool(false)

Zobacz też:



Phar::interceptFileFuncs

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::interceptFileFuncsinstructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Opis

void Phar::interceptFileFuncs ( void )

instructs phar to intercept fopen(), readfile(), file_get_contents(), opendir(), and all of the stat-related functions. If any of these functions is called from within a phar archive with a relative path, the call is modified to access a file within the phar archive. Absolute paths are assumed to be attempts to load external files from the filesystem.

This function makes it possible to run PHP applications designed to run off of a hard disk as a phar application.

Parametry

No parameters.

Zwracane wartości

Przykłady

Przykład #1 A Phar::interceptFileFuncs() example

<?php
Phar
::interceptFileFuncs();
include 
'phar://' __FILE__ '/file.php';
?>

Assuming that this phar is at /path/to/myphar.phar and it contains file.php and file2.txt, if file.php contains this code:

Przykład #2 A Phar::interceptFileFuncs() example

<?php
echo file_get_contents('file2.txt');
?>

Normally PHP would search the current directory for file2.txt, which would translate as the directory of file.php, or the current directory of a command-line user. Phar::interceptFileFuncs() instructs PHP to consider the current directory to be phar:///path/to/myphar.phar/ and so opens phar:///path/to/myphar.phar/file2.txt in the above example code.



Phar::isBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::isBufferingUsed to determine whether Phar write operations are being buffered, or are flushing directly to disk

Opis

bool Phar::isBuffering ( void )

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar::stopBuffering() is needed to enable saving changes.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Zwracane wartości

Returns TRUE if the write operations are being buffer, FALSE otherwise.

Przykłady

Przykład #1 A Phar::isBuffering() example

<?php
$p 
= new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
=2=
<?php
$p
->startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
<?php
var_dump
($p->isBuffering());
var_dump($p2->isBuffering());
?>

Powyższy przykład wyświetli:

bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)

Zobacz też:



Phar::isCompressed

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isCompressedReturns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Opis

mixed Phar::isCompressed ( void )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed as a file, and so this method will always return FALSE if a zip-based phar archive is queried.

Parametry

No parameters.

Zwracane wartości

Phar::GZ, Phar::BZ2 or FALSE

Przykłady

Przykład #1 A Phar::isCompressed() example

<?php
try {
    
$phar1 = new Phar('myphar.zip.phar');
    
var_dump($phar1->isCompressed());
    
$phar2 = new Phar('myuncompressed.tar.phar');
    
var_dump($phar2->isCompressed());
    
$phar2->compressAllFilesGZ();
    
var_dump($phar2->isCompressed() == Phar::GZ);
} catch (
Exception $e) {
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(false)
bool(true)

Zobacz też:



Phar::isFileFormat

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::isFileFormatReturns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Opis

bool Phar::isFileFormat ( int $format )

Parametry

format

Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.

Zwracane wartości

Returns TRUE if the phar archive matches the file format requested by the parameter

Błędy/Wyjątki

PharException is thrown if the parameter is an unknown file format specifier.

Zobacz też:



Phar::isValidPharFilename

(PHP >= 5.3.0, PECL phar >= 1.2.0)

Phar::isValidPharFilenameReturns whether the given filename is a valid phar filename

Opis

bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )

Returns whether the given filename is a valid phar filename that will be recognized as a phar archive by the phar extension. This can be used to test a name without having to instantiate a phar archive and catch the inevitable Exception that will be thrown if an invalid name is specified.

Parametry

filename

The name or full path to a phar archive not yet created

executable

This parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive

Zwracane wartości

Returns TRUE if the filename is valid, FALSE if not.



Phar::isWritable

(Unknown)

Phar::isWritableReturns true if the phar archive can be modified

Opis

bool Phar::isWritable ( void )

This method returns TRUE if phar.readonly is 0, and the actual phar archive on disk is not read-only.

Parametry

No parameters.

Zwracane wartości

Returns TRUE if the phar archive can be modified

Zobacz też:



Phar::loadPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::loadPharLoads any phar archive with an alias

Opis

bool Phar::loadPhar ( string $filename [, string $alias ] )

This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.

Parametry

filename

the full or relative path to the phar archive to open

alias

The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

Przykłady

Przykład #1 A Phar::loadPhar() example

Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.

<?php
try {
    
Phar::loadPhar('/path/to/phar.phar''my.phar');
    echo 
file_get_contents('phar://my.phar/file.txt');
} catch (
PharException $e) {
    echo 
$e;
}
?>

Zobacz też:

  • Phar::mapPhar() - Reads the currently executed file (a phar) and registers its manifest



Phar::mapPhar

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::mapPharReads the currently executed file (a phar) and registers its manifest

Opis

bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )

This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script.

Parametry

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

dataoffset

Unused variable, here for compatibility with PEAR's PHP_Archive.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

PharException is thrown if not called directly within PHP execution, if no __HALT_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading.

Przykłady

Przykład #1 A Phar::mapPhar() example

mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory.

Here is a sample Phar loader stub that uses mapPhar.

<?php
function __autoload($class)
{
    include 
'phar://me.phar/' str_replace('_''/'$class) . '.php';
}
try {
    
Phar::mapPhar('me.phar');
    include 
'phar://me.phar/startup.php';
} catch (
PharException $e) {
    echo 
$e->getMessage();
    die(
'Cannot initialize Phar');
}
__HALT_COMPILER();

Zobacz też:



Phar::mount

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::mountMount an external path or file to a virtual location within the phar archive

Opis

void Phar::mount ( string $pharpath , string $externalpath )

Much like the unix file system concept of mounting external devices to paths within the directory tree, Phar::mount() allows referring to external files and directories as if they were inside of an archive. This allows powerful abstraction such as referring to external configuration files as if they were inside the archive.

Parametry

pharpath

The internal path within the phar archive to use as the mounted path location. This must be a relative path within the phar archive, and must not already exist.

externalpath

A path or URL to an external file or directory to mount within the phar archive

Zwracane wartości

No return. PharException is thrown on failure.

Błędy/Wyjątki

Throws PharException if any problems occur mounting the path.

Przykłady

Przykład #1 A Phar::mount() example

The following example shows accessing an external configuration file as if it were a path within a phar archive.

First, the code inside of a phar archive:

<?php
$configuration 
simplexml_load_string(file_get_contents(
    
Phar::running(false) . '/config.xml'));
?>

Next the external code used to mount the configuration file:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
Phar::mount('phar://config.xml''/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Another method is to put the mounting code inside the stub of the phar archive. Here is an example of setting up a default configuration file if no user configuration is specified:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
if (defined('EXTERNAL_CONFIG')) {
    
Phar::mount('config.xml'EXTERNAL_CONFIG);
    if (
file_exists(__DIR__ '/extra_config.xml')) {
        
Phar::mount('extra.xml'__DIR__ '/extra_config.xml');
    }
} else {
    
Phar::mount('config.xml''phar://' __FILE__ '/default_config.xml');
    
Phar::mount('extra.xml''phar://' __FILE__ '/default_extra.xml');
}
// now run the application
include 'phar://' __FILE__ '/index.php';
__HALT_COMPILER();
?>

...and the code externally to load this phar archive:

<?php
define
('EXTERNAL_CONFIG''/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>



Phar::mungServer

(Unknown)

Phar::mungServerDefines a list of up to 4 $_SERVER variables that should be modified for execution

Opis

void Phar::mungServer ( array $munglist )

Phar::mungServer() should only be called within the stub of a phar archive.

Defines a list of up to 4 $_SERVER variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.

On its own, this method does nothing. Only when combined with Phar::webPhar() does it take effect, and only when the requested file is a PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED variables are always modified.

The original values of variables that are modified are stored in the SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be saved as PHAR_SCRIPT_NAME.

Parametry

munglist

an array containing as string indices any of REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer() is case-sensitive.

Zwracane wartości

No return.

Błędy/Wyjątki

Throws UnexpectedValueException if any problems are found with the passed in data.

Przykłady

Przykład #1 A Phar::mungServer() example

<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>

Zobacz też:

  • Phar::webPhar() - mapPhar for web-based phars. front controller for web applications
  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive



Phar::offsetExists

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetExistsdetermines whether a file exists in the phar

Opis

bool Phar::offsetExists ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.

offsetExists() is called whenever isset() is called.

Parametry

offset

The filename (relative path) to look for in a Phar.

Zwracane wartości

Returns TRUE if the file exists within the phar, or FALSE if not.

Przykłady

Przykład #1 A Phar::offsetExists() example

<?php
$p 
= new Phar(dirname(__FILE__) . '/my.phar'0'my.phar');
$p['firstfile.txt'] = 'first file';
$p['secondfile.txt'] = 'second file';
// the next set of lines call offsetExists() indirectly
var_dump(isset($p['firstfile.txt']));
var_dump(isset($p['nothere.txt']));
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

Zobacz też:



Phar::offsetGet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetGetGets a PharFileInfo object for a specific file

Opis

int Phar::offsetGet ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. Phar::offsetGet() is used for retrieving files from a Phar archive.

Parametry

offset

The filename (relative path) to look for in a Phar.

Zwracane wartości

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

Błędy/Wyjątki

This method throws BadMethodCallException if the file does not exist in the Phar archive.

Przykłady

Przykład #1 Phar::offsetGet() example

As with all classes that implement the ArrayAccess interface, Phar::offsetGet() is automatically called when using the [] angle bracket operator.

<?php
$p 
= new Phar(dirname(__FILE__) . '/myphar.phar'0'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
    
// automatically calls offsetGet()
    
echo $p['exists.txt'];
    echo 
$p['doesnotexist.txt'];
} catch (
BadMethodCallException $e) {
    echo 
$e;
}
?>

Powyższy przykład wyświetli:

file exists
Entry doesnotexist.txt does not exist

Zobacz też:



Phar::offsetSet

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetSetset the contents of an internal file to those of an external file

Opis

void Phar::offsetSet ( string $offset , string $value )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a Phar archive.

Parametry

offset

The filename (relative path) to modify in a Phar.

value

Content of the file.

Zwracane wartości

No return values.

Błędy/Wyjątki

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

Przykłady

Przykład #1 A Phar::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
try {
    
// calls offsetSet
    
$p['file.txt'] = 'Hi there';
} catch (
Exception $e) {
    echo 
'Could not modify file.txt:'$e;
}
?>

Zobacz też:



Phar::offsetUnset

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::offsetUnsetremove a file from a phar

Opis

bool Phar::offsetUnset ( string $offset )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

Parametry

offset

The filename (relative path) to modify in a Phar.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

Przykłady

Przykład #1 A Phar::offsetUnset() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
try {
    
// deletes file.txt from my.phar by calling offsetUnset
    
unset($p['file.txt']);
} catch (
Exception $e) {
    echo 
'Could not delete file.txt: '$e;
}
?>

Zobacz też:



Phar::running

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::runningReturns the full path on disk or full phar URL to the currently executing Phar archive

Opis

string Phar::running ([ bool $retphar = true ] )

Returns the full path to the running phar archive. This is intended for use much like the __FILE__ magic constant, and only has effect inside an executing phar archive.

Inside the stub of an archive, Phar::running() returns "". Simply use __FILE__ to access the current running phar inside a stub.

Parametry

retphar

If FALSE, the full path on disk to the phar archive is returned. If TRUE, a full phar URL is returned.

Zwracane wartości

Returns the filename if valid, empty string otherwise.

Przykłady

Przykład #1 A Phar::running() example

For the following example, assume the phar archive is located at /path/to/phar/my.phar.

<?php
$a 
Phar::running(); // $a is "phar:///path/to/my.phar"
$b Phar::running(false); // $b is "/path/to/my.phar"
?>



Phar::setAlias

(PHP >= 5.3.0, PECL phar >= 1.2.1)

Phar::setAliasSet the alias for the Phar archive

Opis

bool Phar::setAlias ( string $alias )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the phar stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of include() or to use Phar::interceptFileFuncs() and use relative paths.

Parametry

alias

A shorthand string that this archive can be referred to in phar stream wrapper access.

Zwracane wartości

Błędy/Wyjątki

Throws UnexpectedValueException when write access is disabled, and PharException if the alias is already in use or any problems were encountered flushing changes to disk.

Przykłady

Przykład #1 A Phar::setAlias() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
$phar->setAlias('myp.phar');
} catch (
Exception $e) {
    
// handle error
}
?>

Zobacz też:



Phar::setDefaultStub

(Unknown)

Phar::setDefaultStubUsed to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Opis

bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This method is a convenience method that combines the functionality of Phar::createDefaultStub() and Phar::setStub().

Parametry

index

Relative path within the phar archive to run if accessed on the command-line

webindex

Relative path within the phar archive to run if accessed through a web browser

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Przykłady

Przykład #1 A Phar::setDefaultStub() example

<?php
try {
    
$phar = new Phar('myphar.phar');
    
$phar->setDefaultStub('cli.php''web/index.php');
    
// this is the same as:
    // $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
    
// handle errors
}
?>

Zobacz też:



Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadataSets phar archive meta-data

Opis

void Phar::setMetadata ( mixed $metadata )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parametry

metadata

Any PHP variable containing information to store that describes the phar archive

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
    
$p['file.php'] = '<?php echo "hello"';
    
$p->setMetadata(array('bootstrap' => 'file.php'));
    
var_dump($p->getMetadata());
} catch (
Exception $e) {
    echo 
'Could not create and/or modify phar:'$e;
}
?>

Powyższy przykład wyświetli:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

Zobacz też:



Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithmset the signature algorithm for a phar and apply it.

Opis

void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL.

Note that all executable phar archives have a signature created automatically, SHA1 by default. data tar- or zip-based archives (archives created with the PharData class) must have their signature created and set explicitly via Phar::setSignatureAlgorithm().

Parametry

sigtype

One of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL

privatekey

The contents of an OpenSSL private key, as extracted from a certificate or OpenSSL key file:

<?php
$private 
openssl_get_privatekey(file_get_contents('private.pem'));
$pkey '';
openssl_pkey_export($private$pkey);
$p->setSignatureAlgorithm(Phar::OPENSSL$pkey);
?>
See phar introduction for instructions on naming and placement of the public key file.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

Zobacz też:



Phar::setStub

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setStubUsed to set the PHP loader or bootstrap stub of a Phar archive

Opis

bool Phar::setStub ( string $stub )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

<?php
include 'myphar.phar';
?>

The loader is not accessed when including a file through the phar stream wrapper like so:

<?php
include 'phar://myphar.phar/somefile.php';
?>

Parametry

stub

A string or an open stream handle to use as the executable stub for this phar archive.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

Przykłady

Przykład #1 A Phar::setStub() example

<?php
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
    
$p['a.php'] = '<?php var_dump("Hello");';
    
$p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 
'phar://brandnewphar.phar/a.php';
    
var_dump($p->getStub());
    
$p['b.php'] = '<?php var_dump("World");';
    
$p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
    include 
'phar://brandnewphar.phar/b.php';
    
var_dump($p->getStub());
} catch (
Exception $e) {
    echo 
'Write operations failed on brandnewphar.phar: '$e;
}
?>

Powyższy przykład wyświetli:

string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

Zobacz też:



Phar::startBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::startBufferingStart buffering Phar write operations, do not modify the Phar object on disk

Opis

void Phar::startBuffering ( void )

Although technically unnecessary, the Phar::startBuffering() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A Phar::startBuffering() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
} catch (
Exception $e) {
    echo 
'Could not create phar:'$e;
}
echo 
'The new phar has ' $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub("<?php
function __autoload(
$class)
{
    include 'phar://myphar.phar/' . str_replace('_', '/', 
$class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();"
);
$p->stopBuffering();
?>

Zobacz też:

  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk



Phar::stopBuffering

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::stopBufferingStop buffering write requests to the Phar archive, and save changes to disk

Opis

void Phar::stopBuffering ( void )

Phar::stopBuffering() is used in conjunction with the Phar::startBuffering() method. Phar::startBuffering() can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

PharException is thrown if any problems are encountered flushing changes to disk.

Przykłady

Przykład #1 A Phar::stopBuffering() example

<?php
$p 
= new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p->startBuffering();
var_dump($p->getStub());
$p->setStub("<?php
function __autoload(\$class)
{
    include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();"
);
$p->stopBuffering();
var_dump($p->getStub());
?>

Powyższy przykład wyświetli:

string(24) "<?php __HALT_COMPILER();"
string(195) "<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();"

Zobacz też:

  • Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk



Phar::uncompressAllFiles

(PECL phar < 2.0.0)

Phar::uncompressAllFilesUncompresses all files in the current Phar archive

Opis

bool Phar::uncompressAllFiles ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: Phar::compress(), Phar::decompress(), Phar::compressFiles() i Phar::decompressFiles().

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This method decompresses all files in the Phar archive. If any files are already compressed using gzip compression, the zlib extension must be enabled in order to decompress the files, and any files compressed using bzip2 compression require the bzip2 extension to decompress the files. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the bzip2 extension is not enabled and any files are compressed using bzip2 compression, or if any files are compressed using gzip compression and the zlib extension is not enabled.

Przykłady

Przykład #1 A Phar::uncompressAllFiles() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$p['myfile2.txt'] = 'hi';
    
$p->compressAllFilesGZ();
    foreach (
$p as $file) {
        
var_dump($file->getFileName());
        
var_dump($file->isCompressed());
        
var_dump($file->isCompressedBZIP2());
        
var_dump($file->isCompressedGZ());
    }
    
$p->uncompressAllFiles();
    foreach (
$p as $file) {
        
var_dump($file->getFileName());
        
var_dump($file->isCompressed());
        
var_dump($file->isCompressedBZIP2());
        
var_dump($file->isCompressedGZ());
    }
} catch (
Exception $e) {
    echo 
'Write operations failed on my.phar: '$e;
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
bool(true)
bool(false)
bool(true)
string(11) "myfile2.txt"
bool(true)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

Zobacz też:



Phar::unlinkArchive

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::unlinkArchiveCompletely remove a phar archive from disk and from memory

Opis

bool Phar::unlinkArchive ( string $archive )

Removes a phar archive for disk and memory.

Parametry

archive

The path on disk to the phar archive.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

PharException is thrown if there are any open file pointers to the phar archive, or any existing Phar, PharData, or PharFileInfo objects referring to the phar archive.

Przykłady

Przykład #1 A Phar::unlinkArchive() example

<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');

// more common example:
$p = new Phar('my.phar');
$fp fopen('phar://my.phar/file.txt''r');
// this creates 'my.phar.gz'
$gp $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>

Zobacz też:



Phar::webPhar

(PHP >= 5.3.0, PECL phar >= 2.0.0)

Phar::webPharmapPhar for web-based phars. front controller for web applications

Opis

void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )

Phar::mapPhar() for web-based phars. This method parses $_SERVER['REQUEST_URI'] and routes a request from a web browser to an internal file within the phar archive. In essence, it simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. This powerful method is part of what makes it easy to convert an existing PHP application into a phar archive. Combined with Phar::mungServer() and Phar::interceptFileFuncs(), any web application can be used unmodified from a phar archive.

Phar::webPhar() should only be called from the stub of a phar archive (see here for more information on what a stub is).

Parametry

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

index

The location within the phar of the directory index.

f404

The location of the script to run when a file is not found. This script should output the proper HTTP 404 headers.

mimetypes

An array mapping additional file extensions to MIME type. If the default mapping is sufficient, pass an empty array. By default, these extensions are mapped to these MIME types:

<?php
$mimes 
= array(
    
'phps' => Phar::PHPS// pass to highlight_file()
    
'c' => 'text/plain',
    
'cc' => 'text/plain',
    
'cpp' => 'text/plain',
    
'c++' => 'text/plain',
    
'dtd' => 'text/plain',
    
'h' => 'text/plain',
    
'log' => 'text/plain',
    
'rng' => 'text/plain',
    
'txt' => 'text/plain',
    
'xsd' => 'text/plain',
    
'php' => Phar::PHP// parse as PHP
    
'inc' => Phar::PHP// parse as PHP
    
'avi' => 'video/avi',
    
'bmp' => 'image/bmp',
    
'css' => 'text/css',
    
'gif' => 'image/gif',
    
'htm' => 'text/html',
    
'html' => 'text/html',
    
'htmls' => 'text/html',
    
'ico' => 'image/x-ico',
    
'jpe' => 'image/jpeg',
    
'jpg' => 'image/jpeg',
    
'jpeg' => 'image/jpeg',
    
'js' => 'application/x-javascript',
    
'midi' => 'audio/midi',
    
'mid' => 'audio/midi',
    
'mod' => 'audio/mod',
    
'mov' => 'movie/quicktime',
    
'mp3' => 'audio/mp3',
    
'mpg' => 'video/mpeg',
    
'mpeg' => 'video/mpeg',
    
'pdf' => 'application/pdf',
    
'png' => 'image/png',
    
'swf' => 'application/shockwave-flash',
    
'tif' => 'image/tiff',
    
'tiff' => 'image/tiff',
    
'wav' => 'audio/wav',
    
'xbm' => 'image/xbm',
    
'xml' => 'text/xml',
);
?>

rewrites

An array mapping URI to internal file, simulating mod_rewrite of apache. For example:

<?php
array(
    
'myinfo' => 'myinfo.php'
);
?>
would route calls to http://<host>/myphar.phar/myinfo to the file phar:///path/to/myphar.phar/myinfo.php, preserving GET/POST. This does not quite work like mod_rewrite in that it would not match http://<host>/myphar.phar/myinfo/another.

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws PharException when unable to open the internal file to output, or if called from a non-stub. If an invalid array value is passed into mimetypes or to rewrites, then UnexpectedValueException is thrown.

Przykłady

Przykład #1 A Phar::webPhar() example

With the example below, the created phar will display Hello World if one browses to /myphar.phar/index.php or to /myphar.phar, and will display the source of index.phps if one browses to /myphar.phar/index.phps.

<?php
// creating the phar archive:
try {
    
$phar = new Phar('myphar.phar');
    
$phar['index.php'] = '<?php echo "Hello World"; ?>';
    
$phar['index.phps'] = '<?php echo "Hello World"; ?>';
    
$phar->setStub('<?php
Phar::webPhar();
__HALT_COMPILER(); ?>'
);
} catch (
Exception $e) {
    
// handle error here
}
?>

Zobacz też:

  • Phar::mungServer() - Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::interceptFileFuncs() - instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions


Spis treści



The PharData class

(No version information available, might only be in SVN)

Wstęp

The PharData class provides a high-level interface to accessing and creating non-executable tar and zip archives. Because these archives do not contain a stub and cannot be executed by the phar extension, it is possible to create and manipulate regular zip and tar files using the PharData class even if phar.readonly php.ini setting is 1.

Krótki opis klasy

PharData extends Phar {
/* Właściwości */
/* Metody */
bool addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
bool addFromString ( string $localname , string $contents )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array buildFromIterator ( Iterator $iter [, string $base_directory ] )
object compress ( int $compression [, string $extension ] )
bool compressFiles ( int $compression )
__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )
PharData convertToData ([ int $format [, int $compression [, string $extension ]]] )
Phar convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )
bool copy ( string $oldfile , string $newfile )
object decompress ([ string $extension ] )
bool decompressFiles ( void )
bool delMetadata ( void )
bool delete ( string $entry )
bool extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
bool isWritable ( void )
void offsetSet ( string $offset , string $value )
bool offsetUnset ( string $offset )
bool setAlias ( string $alias )
bool setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype )
bool setStub ( string $stub )
/* Metody dziedziczone */
void Phar::addEmptyDir ( string $dirname )
void Phar::addFile ( string $file [, string $localname ] )
void Phar::addFromString ( string $localname , string $contents )
string Phar::apiVersion ( void )
array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )
array Phar::buildFromIterator ( Iterator $iter [, string $base_directory ] )
bool Phar::canCompress ([ int $type = 0 ] )
bool Phar::canWrite ( void )
object Phar::compress ( int $compression [, string $extension ] )
void Phar::compressFiles ( int $compression )
Phar::__construct ( string $fname [, int $flags [, string $alias ]] )
PharData Phar::convertToData ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
Phar Phar::convertToExecutable ([ int $format = 9021976 [, int $compression = 9021976 [, string $extension ]]] )
bool Phar::copy ( string $oldfile , string $newfile )
int Phar::count ( void )
string Phar::createDefaultStub ([ string $indexfile [, string $webindexfile ]] )
object Phar::decompress ([ string $extension ] )
bool Phar::decompressFiles ( void )
bool Phar::delMetadata ( void )
bool Phar::delete ( string $entry )
bool Phar::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )
mixed Phar::getMetadata ( void )
bool Phar::getModified ( void )
array Phar::getSignature ( void )
string Phar::getStub ( void )
string Phar::getVersion ( void )
bool Phar::hasMetadata ( void )
bool Phar::isBuffering ( void )
mixed Phar::isCompressed ( void )
bool Phar::isFileFormat ( int $format )
bool Phar::isValidPharFilename ( string $filename [, bool $executable = true ] )
bool Phar::isWritable ( void )
bool Phar::loadPhar ( string $filename [, string $alias ] )
bool Phar::mapPhar ([ string $alias [, int $dataoffset = 0 ]] )
void Phar::mount ( string $pharpath , string $externalpath )
void Phar::mungServer ( array $munglist )
bool Phar::offsetExists ( string $offset )
int Phar::offsetGet ( string $offset )
void Phar::offsetSet ( string $offset , string $value )
bool Phar::offsetUnset ( string $offset )
string Phar::running ([ bool $retphar = true ] )
bool Phar::setAlias ( string $alias )
bool Phar::setDefaultStub ([ string $index [, string $webindex ]] )
void Phar::setMetadata ( mixed $metadata )
void Phar::setSignatureAlgorithm ( int $sigtype [, string $privatekey ] )
bool Phar::setStub ( string $stub )
void Phar::startBuffering ( void )
void Phar::stopBuffering ( void )
bool Phar::unlinkArchive ( string $archive )
void Phar::webPhar ([ string $alias [, string $index = "index.php" [, string $f404 [, array $mimetypes [, array $rewrites ]]]]] )
}

PharData::addEmptyDir

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addEmptyDirAdd an empty directory to the tar/zip archive

Opis

bool PharData::addEmptyDir ( string $dirname )

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

Parametry

dirname

The name of the empty directory to create in the phar archive

Zwracane wartości

no return value, exception is thrown on failure.

Przykłady

Przykład #1 A PharData::addEmptyDir() example

<?php
try {
    
$a = new PharData('/path/to/my.tar');

    
$a->addEmptyDir('/full/path/to/file');
    
// demonstrates how this file is stored
    
$b $a['full/path/to/file']->isDir();
} catch (
Exception $e) {
    
// handle errors here
}
?>

Zobacz też:



PharData::addFile

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFileAdd a file from the filesystem to the tar/zip archive

Opis

void Phar::addFile ( string $file [, string $localname ] )

With this method, any file or URL can be added to the tar/zip archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

Parametry

file

Full or relative path to a file on disk to be added to the phar archive.

localname

Path that the file will be stored in the archive.

Zwracane wartości

no return value, exception is thrown on failure.

Przykłady

Przykład #1 A PharData::addFile() example

<?php
try {
    
$a = new PharData('/path/to/my.tar');

    
$a->addFile('/full/path/to/file');
    
// demonstrates how this file is stored
    
$b $a['full/path/to/file']->getContent();

    
$a->addFile('/full/path/to/file''my/file.txt');
    
$c $a['my/file.txt']->getContent();

    
// demonstrate URL usage
    
$a->addFile('http://www.example.com''example.html');
} catch (
Exception $e) {
    
// handle errors here
}
?>

Zobacz też:



PharData::addFromString

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::addFromStringAdd a file from the filesystem to the tar/zip archive

Opis

bool PharData::addFromString ( string $localname , string $contents )

With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

Parametry

localname

Path that the file will be stored in the archive.

contents

The file contents to store

Zwracane wartości

no return value, exception is thrown on failure.

Przykłady

Przykład #1 A PharData::addFromString() example

<?php
try {
    
$a = new PharData('/path/to/my.tar');

    
$a->addFromString('path/to/file.txt''my simple file');
    
$b $a['path/to/file.txt']->getContent();

    
// to add contents from a stream handle for large files, use offsetSet()
    
$c fopen('/path/to/hugefile.bin');
    
$a['largefile.bin'] = $c;
    
fclose($c);
} catch (
Exception $e) {
    
// handle errors here
}
?>

Zobacz też:



PharData::buildFromDirectory

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromDirectoryConstruct a tar/zip archive from the files within a directory.

Opis

array Phar::buildFromDirectory ( string $base_dir [, string $regex ] )

Populate a tar/zip archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use PharData::buildFromIterator().

Parametry

base_dir

The full or relative path to the directory that contains all files to add to the archive.

regex

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

Zwracane wartości

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Błędy/Wyjątki

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

Przykłady

Przykład #1 A PharData::buildFromDirectory() example

<?php
$phar 
= new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');

$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar->buildFromDirectory(dirname(__FILE__) . '/project''/\.php$/');
?>

Zobacz też:



PharData::buildFromIterator

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::buildFromIteratorConstruct a tar or zip archive from an iterator.

Opis

array PharData::buildFromIterator ( Iterator $iter [, string $base_directory ] )

Populate a tar or zip archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the tar/zip to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

Przykłady

Przykład #1 A PharData::buildFromIterator() with SplFileInfo

For most tar/zip archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a tar/zip archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.tar" tar archive:

<?php
$phar 
= new PharData('project.tar');
$phar->buildFromIterator(
    new 
RecursiveIteratorIterator(
     new 
RecursiveDirectoryIterator('/path/to/project')),
    
'/path/to/project');
?>

The file project.tar can then be used immediately. PharData::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the tar/zip archive.

As an interesting note, PharData::buildFromIterator() can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from DirectoryIterator:

<?php
$phar 
= new PharData('project.tar');
$phar->buildFromIterator(
    new 
RecursiveIteratorIterator(
     new 
Phar('/path/to/anotherphar.phar')),
    
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php''www/index.php'));
?>

Przykład #2 A PharData::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
$phar 
= new PharData('project.tar');
$phar->buildFromIterator(
    new 
ArrayIterator(
     array(
        
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
        
'another/file.jpg' => fopen('/path/to/bigfile.jpg''rb'),
     )));
?>

Parametry

iter

Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

base_directory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the tar/zip archive

Zwracane wartości

PharData::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

Błędy/Wyjątki

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a base_directory parameter, or a PharException if there were errors saving the phar archive.

Zobacz też:



PharData::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compressCompresses the entire tar/zip archive using Gzip or Bzip2 compression

Opis

object PharData::compress ( int $compression [, string $extension ] )

For tar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For zip archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

Parametry

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .tar.gz or .tar.bz2 for compressing a tar, and .tar for decompressing.

Zwracane wartości

A PharData object is returned.

Błędy/Wyjątki

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Przykłady

Przykład #1 A PharData::compress() example

<?php
$p 
= new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

Zobacz też:

  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression



PharData::compressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::compressFilesCompresses all files in the current tar/zip archive

Opis

bool PharData::compressFiles ( int $compression )

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method compresses all files in the archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing.

Parametry

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Przykłady

Przykład #1 A PharData::compressFiles() example

<?php
$p 
= new Phar('/path/to/my.phar'0'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

Zobacz też:



PharData::__construct

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::__constructConstruct a non-executable tar or zip archive object

Opis

PharData::__construct ( string $fname [, int $flags [, string $alias [, int $format = Phar::TAR ]]] )

Parametry

fname

Path to an existing tar/zip archive or to-be-created archive

flags

Flags to pass to Phar parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

format

One of the file format constants available within the Phar class.

Błędy/Wyjątki

Throws BadMethodCallException if called twice; UnexpectedValueException if the Phar archive can't be opened.

Przykłady

Przykład #1 A PharData::__construct() example

<?php
try {
    
$p = new PharData('/path/to/my.tar'CURRENT_AS_FILEINFO KEY_AS_FILENAME);
} catch (
UnexpectedValueException $e) {
    die(
'Could not open my.tar');
} catch (
BadMethodCallException $e) {
    echo 
'technically, this cannot happen';
}
echo 
file_get_contents('phar:///path/to/my.tar/example.txt');
?>



PharData::convertToData

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToDataConvert a phar archive to a non-executable tar or zip file

Opis

PharData PharData::convertToData ([ int $format [, int $compression [, string $extension ]]] )

This method is used to convert a non-executable tar or zip archive to another non-executable format.

If no changes are specified, this method throws a BadMethodCallException. This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the PharData::compress() method for logical consistency.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parametry

format

This should be one of Phar::TAR or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

Zwracane wartości

The method returns a PharData object on success and throws an exception on failure.

Błędy/Wyjątki

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

Przykłady

Przykład #1 A PharData::convertToData() example

Using PharData::convertToData():

<?php
try {
    
$tarphar = new PharData('myphar.tar');
    
// note that myphar.tar is *not* unlinked
    // convert it to the non-executable tar file format
    // creates myphar.zip
    
$zip $tarphar->convertToData(Phar::ZIP);
    
// create myphar.tbz
    
$tgz $zip->convertToData(Phar::TARPhar::BZ2'.tbz');
    
// creates myphar.phar.tgz
    
$phar $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
    
// handle the error here
}
?>

Zobacz też:



PharData::convertToExecutable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::convertToExecutableConvert a non-executable tar/zip archive to an executable phar archive

Opis

Phar PharData::convertToExecutable ([ int $format [, int $compression [, string $extension ]]] )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

Parametry

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to NULL, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

Zwracane wartości

The method returns a Phar object on success and throws an exception on failure.

Błędy/Wyjątki

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

Przykłady

Przykład #1 A PharData::convertToExecutable() example

Using PharData::convertToExecutable():

<?php
try {
    
$tarphar = new PharData('myphar.tar');
    
// convert it to the phar file format
    // note that myphar.tar is *not* unlinked
    
$phar $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
    
$phar->setStub($phar->createDefaultStub('cli.php''web/index.php'));
    
// creates myphar.phar.tgz
    
$compressed $tarphar->convertToExecutable(Phar::TARPhar::GZ'.phar.tgz');
} catch (
Exception $e) {
    
// handle the error here
}
?>

Zobacz też:



PharData::copy

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::copyCopy a file internal to the phar archive to another new file within the phar

Opis

bool PharData::copy ( string $oldfile , string $newfile )

Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using copy() with the phar stream wrapper.

Parametry

oldfile

newfile

Zwracane wartości

returns TRUE on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

Błędy/Wyjątki

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

Przykłady

Przykład #1 A PharData::copy() example

This example shows using PharData::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
    
$phar = new PharData('myphar.tar');
    
$phar['a'] = 'hi';
    
$phar->copy('a''b');
    echo 
$phar['b']; // outputs "phar://myphar.tar/b"
} catch (Exception $e) {
    
// handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a''phar//myphar.tar/c');
echo 
file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>



PharData::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompressDecompresses the entire Phar archive

Opis

object PharData::decompress ([ string $extension ] )

For tar-based archives, this method decompresses the entire archive.

For Zip-based archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression.

In addition, this method automatically renames the file extension of the archive, .tar by default. Alternatively, a file extension may be specified with the second parameter.

Parametry

extension

For decompressing, the default file extension is .phar.tar. Use this parameter to specify another file extension. Be aware that no non-executable archives cannot contain .phar in their filename.

Zwracane wartości

A PharData object is returned.

Błędy/Wyjątki

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

Przykłady

Przykład #1 A PharData::decompress() example

<?php
$p 
= new PharData('/path/to/my.tar'0'my.tar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 $p2->decompress(); // creates /path/to/my.tar
?>

Zobacz też:



PharData::decompressFiles

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::decompressFilesDecompresses all files in the current zip archive

Opis

bool PharData::decompressFiles ( void )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method decompresses all files in the archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

Przykłady

Przykład #1 A PharData::decompressFiles() example

<?php
$p 
= new PharData('/path/to/my.zip');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach (
$p as $file) {
    
var_dump($file->getFileName());
    
var_dump($file->isCompressed());
    
var_dump($file->isCompressed(Phar::BZ2));
    
var_dump($file->isCompressed(Phar::GZ));
}
?>

Powyższy przykład wyświetli:

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

Zobacz też:



PharData::delMetadata

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::delMetadataDeletes the global metadata of a zip archive

Opis

bool PharData::delMetadata ( void )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Deletes the global metadata of the zip archive

Parametry

Zwracane wartości

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Błędy/Wyjątki

Throws PharException if errors occur while flushing changes to disk.

Przykłady

Przykład #1 A PharData::delMetaData() example

<?php
try {
    
$phar = new PharData('myphar.zip');
    
var_dump($phar->getMetadata());
    
$phar->setMetadata("hi there");
    
var_dump($phar->getMetadata());
    
$phar->delMetadata();
    
var_dump($phar->getMetadata());
} catch (
Exception $e) {
    
// handle errors
}
?>

Powyższy przykład wyświetli:

NULL
string(8) "hi there"
NULL

Zobacz też:



PharData::delete

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::deleteDelete a file within a tar/zip archive

Opis

bool PharData::delete ( string $entry )

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

Parametry

entry

Path within an archive to the file to delete.

Zwracane wartości

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Błędy/Wyjątki

Throws PharException if errors occur while flushing changes to disk.

Przykłady

Przykład #1 A PharData::delete() example

<?php
try {
    
$phar = new PharData('myphar.zip');
    
$phar->delete('unlink/me.php');
    
// this is equivalent to:
    
unlink('phar://myphar.phar/unlink/me.php');
} catch (
Exception $e) {
    
// handle errors
}
?>

Zobacz też:



PharData::extractTo

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::extractToExtract the contents of a tar/zip archive to a directory

Opis

bool PharData::extractTo ( string $pathto [, string|array $files [, bool $overwrite = false ]] )

Extract all files within a tar/zip archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

Parametry

pathto

Path within an archive to the file to delete.

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to TRUE to enable overwriting existing files

Zwracane wartości

returns TRUE on success, but it is better to check for thrown exception, and assume success if none is thrown.

Błędy/Wyjątki

Throws PharException if errors occur while flushing changes to disk.

Przykłady

Przykład #1 A PharData::extractTo() example

<?php
try {
    
$phar = new PharData('myphar.tar');
    
$phar->extractTo('/full/path'); // extract all files
    
$phar->extractTo('/another/path''file.txt'); // extract only file.txt
    
$phar->extractTo('/this/path',
        array(
'file1.txt''file2.txt')); // extract 2 files only
    
$phar->extractTo('/third/path'nulltrue); // extract all files, and overwrite
} catch (Exception $e) {
    
// handle errors
}
?>

Zobacz też:



PharData::isWritable

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::isWritableReturns true if the tar/zip archive can be modified

Opis

bool PharData::isWritable ( void )

This method returns TRUE if the tar/zip archive on disk is not read-only. Unlike Phar::isWritable(), data-only tar/zip archives can be modified even if phar.readonly is set to 1.

Parametry

No parameters.

Zwracane wartości

Returns TRUE if the tar/zip archive can be modified

Zobacz też:



PharData::offsetSet

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetSetset the contents of a file within the tar/zip to those of an external file or string

Opis

void PharData::offsetSet ( string $offset , string $value )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive.

Parametry

offset

The filename (relative path) to modify in a tar or zip archive.

value

Content of the file.

Zwracane wartości

No return values.

Błędy/Wyjątki

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Przykłady

Przykład #1 A PharData::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p 
= new PharData('/path/to/my.tar');
try {
    
// calls offsetSet
    
$p['file.txt'] = 'Hi there';
} catch (
Exception $e) {
    echo 
'Could not modify file.txt:'$e;
}
?>

Zobacz też:

  • Phar::offsetSet() - set the contents of an internal file to those of an external file



PharData::offsetUnset

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::offsetUnsetremove a file from a tar/zip archive

Opis

bool PharData::offsetUnset ( string $offset )

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

Parametry

offset

The filename (relative path) to modify in the tar/zip archive.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

Przykłady

Przykład #1 A PharData::offsetUnset() example

<?php
$p 
= new PharData('/path/to/my.zip');
try {
    
// deletes file.txt from my.zip by calling offsetUnset
    
unset($p['file.txt']);
} catch (
Exception $e) {
    echo 
'Could not delete file.txt: '$e;
}
?>

Zobacz też:



PharData::setAlias

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setAliasdummy function (Phar::setAlias is not valid for PharData)

Opis

bool PharData::setAlias ( string $alias )

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

Parametry

alias

A shorthand string that this archive can be referred to in phar stream wrapper access. This parameter is ignored.

Zwracane wartości

Błędy/Wyjątki

Throws PharException on all method calls

Zobacz też:



PharData::setDefaultStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setDefaultStubdummy function (Phar::setDefaultStub is not valid for PharData)

Opis

bool PharData::setDefaultStub ([ string $index [, string $webindex ]] )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parametry

index

Relative path within the phar archive to run if accessed on the command-line

webindex

Relative path within the phar archive to run if accessed through a web browser

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws PharException on all method calls

Zobacz też:

  • Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader



Phar::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

Phar::setMetadataSets phar archive meta-data

Opis

void Phar::setMetadata ( mixed $metadata )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

Parametry

metadata

Any PHP variable containing information to store that describes the phar archive

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
    
$p['file.php'] = '<?php echo "hello"';
    
$p->setMetadata(array('bootstrap' => 'file.php'));
    
var_dump($p->getMetadata());
} catch (
Exception $e) {
    echo 
'Could not create and/or modify phar:'$e;
}
?>

Powyższy przykład wyświetli:

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

Zobacz też:



Phar::setSignatureAlgorithm

(PHP >= 5.3.0, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithmset the signature algorithm for a phar and apply it. The

Opis

void Phar::setSignatureAlgorithm ( int $sigtype )

Informacja:

Ta metoda wymaga ustawienia w php.ini wartości phar.readonly na 0 aby działała z obiektami Phar. W przeciwnym przypadku, klasa PharException zwróci wyjątek .

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::PGP (pgp not yet supported and falls back to SHA-1).

Parametry

sigtype

One of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::PGP

Zwracane wartości

Nie jest zwracana żadna wartość.

Błędy/Wyjątki

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a PharException if any problems occur flushing changes to disk.

Zobacz też:



PharData::setStub

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharData::setStubdummy function (Phar::setStub is not valid for PharData)

Opis

bool PharData::setStub ( string $stub )

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

Parametry

stub

A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws PharException on all method calls

Zobacz też:

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive


Spis treści



The PharFileInfo class

(No version information available, might only be in SVN)

Wstęp

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

Krótki opis klasy

PharFileInfo extends SplFileInfo {
/* Właściwości */
/* Metody */
void chmod ( int $permissions )
bool compress ( int $compression )
__construct ( string $entry )
bool decompress ( void )
bool delMetadata ( void )
int getCRC32 ( void )
int getCompressedSize ( void )
mixed getMetadata ( void )
int getPharFlags ( void )
bool hasMetadata ( void )
bool isCRCChecked ( void )
bool isCompressed ([ int $compression_type = 9021976 ] )
bool isCompressedBZIP2 ( void )
bool isCompressedGZ ( void )
bool setCompressedBZIP2 ( void )
bool setCompressedGZ ( void )
void setMetadata ( mixed $metadata )
bool setUncompressed ( void )
}

PharFileInfo::chmod

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::chmodSets file-specific permission bits

Opis

void PharFileInfo::chmod ( int $permissions )

PharFileInfo::chmod() allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Parametry

permissions

permissions (see chmod())

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A PharFileInfo::chmod() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar('brandnewphar.phar'0'brandnewphar.phar');
    
$p['file.sh'] = '#!/usr/local/lib/php
    <?php echo "hi"; ?>'
;
    
// set executable bit
    
$p['file.sh']->chmod(0555);
    
var_dump($p['file.sh']->isExecutable());
} catch (
Exception $e) {
    echo 
'Could not create/modify phar: '$e;
}
?>

Powyższy przykład wyświetli:

bool(true)



PharFileInfo::compress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::compressCompresses the current Phar entry with either zlib or bzip2 compression

Opis

bool PharFileInfo::compress ( int $compression )

This method compresses the file inside the Phar archive using either bzip2 compression or zlib compression. The bzip2 or zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed, the respective extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Przykłady

Przykład #1 A PharFileInfo::compress() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
var_dump($file->isCompressed(Phar::BZ2));
    
$p['myfile.txt']->compress(Phar::BZ2);
    
var_dump($file->isCompressed(Phar::BZ2));
} catch (
Exception $e) {
    echo 
'Create/modify operations on my.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:



PharFileInfo::__construct

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::__constructConstruct a Phar entry object

Opis

PharFileInfo::__construct ( string $entry )

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

Parametry

entry

The full url to retrieve a file. If you wish to retrieve the information for the file my/file.php from the phar boo.phar, the entry should be phar://boo.phar/my/file.php.

Błędy/Wyjątki

Throws BadMethodCallException if __construct() is called twice. Throws UnexpectedValueException if the phar URL requested is malformed, the requested phar cannot be opened, or the file can't be found within the phar.

Przykłady

Przykład #1 A PharFileInfo::__construct() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['testfile.txt'] = "hi\nthere\ndude";
    
$file $p['testfile.txt'];
    foreach (
$file as $line => $text) {
        echo 
"line number $line$text";
    }
    
// this also works
    
$file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
    foreach (
$file as $line => $text) {
        echo 
"line number $line$text";
    }
} catch (
Exception $e) {
    echo 
'Phar operations failed: '$e;
}
?>

Powyższy przykład wyświetli:

line number 1: hi
line number 2: there
line number 3: dude
line number 1: hi
line number 2: there
line number 3: dude



PharFileInfo::decompress

(PHP >= 5.3.0, PECL phar >= 2.0.0)

PharFileInfo::decompressDecompresses the current Phar entry within the phar

Opis

bool PharFileInfo::decompress ( void )

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Przykłady

Przykład #1 A PharFileInfo::decompress() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
$file->compress(Phar::GZ);
    
var_dump($file->isCompressed());
    
$p['myfile.txt']->decompress();
    
var_dump($file->isCompressed());
} catch (
Exception $e) {
    echo 
'Create/modify failed for my.phar: '$e;
}
?>

Powyższy przykład wyświetli:

int(4096)
bool(false)

Zobacz też:



PharFileInfo::delMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::delMetadataDeletes the metadata of the entry

Opis

bool PharFileInfo::delMetadata ( void )

Deletes the metadata of the entry, if any.

Parametry

No parameters.

Zwracane wartości

Returns TRUE if successful, FALSE if the entry had no metadata. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Błędy/Wyjątki

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

Przykłady

Przykład #1 A PharFileInfo::delMetaData() example

<?php
try {
    
$a = new Phar('myphar.phar');
    
$a['hi'] = 'hi';
    
var_dump($a['hi']->delMetadata());
    
$a['hi']->setMetadata('there');
    
var_dump($a['hi']->delMetadata());
    
var_dump($a['hi']->delMetadata());
} catch (
Exception $e) {
    
// handle errors
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)
bool(false)

Zobacz też:



PharFileInfo::getCRC32

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCRC32Returns CRC32 code or throws an exception if CRC has not been verified

Opis

int PharFileInfo::getCRC32 ( void )

This returns the crc32() checksum of the file within the Phar archive.

Zwracane wartości

The crc32() checksum of the file within the Phar archive.

Błędy/Wyjątki

Throws BadMethodCallException if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing.

Przykłady

Przykład #1 A PharFileInfo::getCRC32() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    echo 
$file->getCRC32();
} catch (
Exception $e) {
    echo 
'Write operations on my.phar.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

3633523372



PharFileInfo::getCompressedSize

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSizeReturns the actual size of the file (with compression) inside the Phar archive

Opis

int PharFileInfo::getCompressedSize ( void )

This returns the size of the file within the Phar archive. Uncompressed files will return the same value for getCompressedSize as they will with filesize()

Zwracane wartości

The size in bytes of the file within the Phar archive on disk.

Przykłady

Przykład #1 A PharFileInfo::getCompressedSize() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    echo 
$file->getCompressedSize();
} catch (
Exception $e) {
    echo 
'Write operations failed on my.phar: '$e;
}
?>

Powyższy przykład wyświetli:

2

Zobacz też:



PharFileInfo::getMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getMetadataReturns file-specific meta-data saved with a file

Opis

mixed PharFileInfo::getMetadata ( void )

Return meta-data that was saved in the Phar archive's manifest for this file.

Parametry

Zwracane wartości

any PHP variable that can be serialized and is stored as meta-data for the file, or NULL if no meta-data is stored.

Przykłady

Przykład #1 A PharFileInfo::getMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
    
$p['file.txt'] = 'hello';
    
$p['file.txt']->setMetadata(array('user' => 'bill''mime-type' => 'text/plain'));
    
var_dump($p['file.txt']->getMetadata());
} catch (
Exception $e) {
    echo 
'Could not create/modify brandnewphar.phar: '$e;
}
?>

Powyższy przykład wyświetli:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

Zobacz też:



PharFileInfo::getPharFlags

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::getPharFlagsReturns the Phar file entry flags

Opis

int PharFileInfo::getPharFlags ( void )

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

Zwracane wartości

The Phar flags (always 0 in the current implementation)

Przykłady

Przykład #1 A PharFileInfo::getPharFlags() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
var_dump($file->getPharFlags());
} catch (
Exception $e) {
    echo 
'Could not create/modify my.phar: '$e;
}
?>

Powyższy przykład wyświetli:

int(0)



PharFileInfo::hasMetadata

(PHP >= 5.3.0, PECL phar >= 1.2.0)

PharFileInfo::hasMetadataReturns the metadata of the entry

Opis

bool PharFileInfo::hasMetadata ( void )

Returns the metadata of a file within a phar archive.

Parametry

No parameters.

Zwracane wartości

Returns FALSE if no metadata is set or is NULL, TRUE if metadata is not NULL

Zobacz też:



PharFileInfo::isCRCChecked

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCRCCheckedReturns whether file entry has had its CRC verified

Opis

bool PharFileInfo::isCRCChecked ( void )

This returns whether a file within a Phar archive has had its CRC verified.

Zwracane wartości

TRUE if the file has had its CRC verified, FALSE if not.

Przykłady

Przykład #1 A PharFileInfo::isCRCChecked() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
var_dump($file->isCRCChecked());
} catch (
Exception $e) {
    echo 
'Create/modify operations failed on my.phar: '$e;
}
?>

Powyższy przykład wyświetli:

bool(true)



PharFileInfo::isCompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedReturns whether the entry is compressed

Opis

bool PharFileInfo::isCompressed ([ int $compression_type = 9021976 ] )

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

Parametry

compression_type

One of Phar::GZ or Phar::BZ2, defaults to any compression.

Zwracane wartości

TRUE if the file is compressed within the Phar archive, FALSE if not.

Przykłady

Przykład #1 A PharFileInfo::isCompressed() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$p['myfile2.txt'] = 'hi';
    
$p['myfile2.txt']->setCompressedGZ();
    
$file $p['myfile.txt'];
    
$file2 $p['myfile2.txt'];
    
var_dump($file->isCompressed());
    
var_dump($file2->isCompressed());
} catch (
Exception $e) {
    echo 
'Create/modify on phar my.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:



PharFileInfo::isCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedBZIP2Returns whether the entry is compressed using bzip2

Opis

bool PharFileInfo::isCompressedBZIP2 ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: PharFileInfo::isCompressed(), PharFileInfo::decompress(), i PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Bzip2 compression.

Zwracane wartości

TRUE if the file is compressed within the Phar archive using Bzip2, FALSE if not.

Przykłady

Przykład #1 A PharFileInfo::isCompressedBZIP2() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$p['myfile2.txt'] = 'hi';
    
$p['myfile3.txt'] = 'hi';
    
$p['myfile2.txt']->setCompressedGZ();
    
$p['myfile3.txt']->setCompressedBZIP2();
    
$file $p['myfile.txt'];
    
$file2 $p['myfile2.txt'];
    
$file3 $p['myfile3.txt'];
    
var_dump($file->isCompressedBZIP2());
    
var_dump($file2->isCompressedBZIP2());
    
var_dump($file3->isCompressedBZIP2());
} catch (
Exception $e) {
    echo 
'Create/modify on phar my.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(false)
bool(true)

Zobacz też:



PharFileInfo::isCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::isCompressedGZReturns whether the entry is compressed using gz

Opis

bool PharFileInfo::isCompressedGZ ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: PharFileInfo::isCompressed(), PharFileInfo::decompress(), i PharFileInfo::compress().

This returns whether a file is compressed within a Phar archive with Gzip compression.

Zwracane wartości

TRUE if the file is compressed within the Phar archive using Gzip, FALSE if not.

Przykłady

Przykład #1 A PharFileInfo::isCompressedGZ() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$p['myfile2.txt'] = 'hi';
    
$p['myfile3.txt'] = 'hi';
    
$p['myfile2.txt']->setCompressedGZ();
    
$p['myfile3.txt']->setCompressedBZIP2();
    
$file $p['myfile.txt'];
    
$file2 $p['myfile2.txt'];
    
$file3 $p['myfile3.txt'];
    
var_dump($file->isCompressedGZ());
    
var_dump($file2->isCompressedGZ());
    
var_dump($file3->isCompressedGZ());
} catch (
Exception $e) {
    echo 
'Create/modify on phar my.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)
bool(false)

Zobacz też:



PharFileInfo::setCompressedBZIP2

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedBZIP2Compresses the current Phar entry within the phar using Bzip2 compression

Opis

bool PharFileInfo::setCompressedBZIP2 ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: PharFileInfo::isCompressed(), PharFileInfo::decompress(), i PharFileInfo::compress().

This method compresses the file inside the Phar archive using bzip2 compression. The bzip2 extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using gzip compression, the zlib extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2 extension is not available.

Przykłady

Przykład #1 A PharFileInfo::setCompressedBZIP2() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
var_dump($file->isCompressedBZIP2());
    
$p['myfile.txt']->setCompressedBZIP2();
    
var_dump($file->isCompressedBZIP2());
} catch (
Exception $e) {
    echo 
'Create/modify operations on my.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:



PharFileInfo::setCompressedGZ

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setCompressedGZCompresses the current Phar entry within the phar using gz compression

Opis

bool PharFileInfo::setCompressedGZ ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: PharFileInfo::isCompressed(), PharFileInfo::decompress(), i PharFileInfo::compress().

This method compresses the file inside the Phar archive using gzip compression. The zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed using bzip2 compression, the bzip2 extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the zlib extension is not available.

Przykłady

Przykład #1 A PharFileInfo::setCompressedGZ() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
var_dump($file->isCompressedGZ());
    
$p['myfile.txt']->setCompressedGZ();
    
var_dump($file->isCompressedGZ());
} catch (
Exception $e) {
    echo 
'Create/modify operations on my.phar failed: '$e;
}
?>

Powyższy przykład wyświetli:

bool(false)
bool(true)

Zobacz też:



PharFileInfo::setMetadata

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setMetadataSets file-specific meta-data saved with a file

Opis

void PharFileInfo::setMetadata ( mixed $metadata )

PharFileInfo::setMetadata() should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod() method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

Parametry

metadata

Any PHP variable containing information to store alongside a file

Zwracane wartości

Nie jest zwracana żadna wartość.

Przykłady

Przykład #1 A PharFileInfo::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar'0'brandnewphar.phar');
    
$p['file.txt'] = 'hello';
    
$p['file.txt']->setMetadata(array('user' => 'bill''mime-type' => 'text/plain'));
    
var_dump($p['file.txt']->getMetaData());
} catch (
Exception $e) {
    echo 
'Could not create/modify phar: '$e;
}
?>

Powyższy przykład wyświetli:

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

Zobacz też:



PharFileInfo::setUncompressed

(PHP >= 5.3.0, PECL phar >= 1.0.0)

PharFileInfo::setUncompressedUncompresses the current Phar entry within the phar, if it is compressed

Opis

bool PharFileInfo::setUncompressed ( void )

Informacja:

Ta metoda została usunięta z rozszerzenia phar w wersji 2.0.0. Dostępne są zastępcze implementacje: PharFileInfo::isCompressed(), PharFileInfo::decompress(), i PharFileInfo::compress().

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Błędy/Wyjątki

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

Przykłady

Przykład #1 A PharFileInfo::setUncompressed() example

<?php
try {
    
$p = new Phar('/path/to/my.phar'0'my.phar');
    
$p['myfile.txt'] = 'hi';
    
$file $p['myfile.txt'];
    
$file->setCompressedGZ();
    
var_dump($file->isCompressed());
    
$p['myfile.txt']->setUncompressed();
    
var_dump($file->isCompressed());
} catch (
Exception $e) {
    echo 
'Create/modify failed for my.phar: '$e;
}
?>

Powyższy przykład wyświetli:

bool(true)
bool(false)

Zobacz też:


Spis treści



The PharException class

(Unknown)

Wstęp

The PharException class provides a phar-specific exception class for try/catch blocks.

Krótki opis klasy

PharException extends Exception {
/* Właściwości */
}

PharException

(Unknown)

PharExceptionThe PharException class provides a phar-specific exception class for try/catch blocks.

Opis


Spis treści

  • PharException — The PharException class provides a phar-specific exception class for try/catch blocks.



Rar Archiving


Wstęp

Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by the UnRar library and is directly prohibited by its license.

More information about Rar and UnRar can be found at » http://www.rarlabs.com/.



Instalacja/Konfiguracja

Spis treści


Wymagania

Do zbudowania tego rozszerzenia nie są wymagane żadne zewnętrzne biblioteki.



Instalacja

Rar is currently available through PECL » http://pecl.php.net/package/rar.

Also you can use the PECL installer to install the Rar extension, using the following command: pecl -v install rar.

You can always download the tar.gz package and install Rar by hand:

Przykład #1 Rar installation

gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install

Windows users will enable php_rar.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/



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

This extension registers three internal classes: The archive representations returned by rar_open()RarArchive –, the entry representations returned by rar_list() and rar_entry_get()RarEntry and the exception type RarException.

This extension also register a stream resource, called "rar" and a URL wrapper called "rar wrapper" and registered under the prefix "rar".




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.

RAR_HOST_MSDOS (integer)
Use RarEntry::HOST_MSDOS instead.
RAR_HOST_OS2 (integer)
Use RarEntry::HOST_OS2 instead.
RAR_HOST_WIN32 (integer)
Use RarEntry::HOST_WIN32 instead.
RAR_HOST_UNIX (integer)
Use RarEntry::HOST_UNIX instead.
RAR_HOST_BEOS (integer)
Use RarEntry::HOST_BEOS instead.


Przykłady

See also the examples under rar:// wrapper.

Przykład #1 On-the-fly decompression

<?php

if (!array_key_exists("i"$_GET) || !is_numeric($_GET["i"]))
    die(
"Index unspecified or non-numeric");
$index = (int) $_GET["i"];
    
$arch RarArchive::open("example.rar");
if (
$arch === FALSE)
    die(
"Cannot open example.rar");

$entries $arch->getEntries();
if (
$entries === FALSE)
    die(
"Cannot retrieve entries");

if (!
array_key_exists($index$entries))
    die(
"No such index: $index");

$orfilename $entries[$index]->getName(); //UTF-8 encoded

$filesize $entries[$index]->getUnpackedSize();

/* you could check HTTP_IF_MODIFIED_SINCE here and compare with
 * $entries[$index]->getFileTime(). You could also send a
 * "Last modified" header */

$fp $entries[$index]->getStream();
if (
$fp === FALSE)
    die(
"Cannot open file with index $index insided the archive.");

$arch->close(); //no longer needed; stream is independent

function detectUserAgent() {
    if (!
array_key_exists('HTTP_USER_AGENT'$_SERVER))
        return 
"Other";
    
    
$uas $_SERVER['HTTP_USER_AGENT'];
    if (
preg_match("@Opera/@"$uas))
        return 
"Opera";
    if (
preg_match("@Firefox/@"$uas))
        return 
"Firefox";
    if (
preg_match("@Chrome/@"$uas))
        return 
"Chrome";
    if (
preg_match("@MSIE ([0-9.]+);@"$uas$matches)) {
        if (((float)
$matches[1]) >= 7.0)
            return 
"IE";
    }
    
    return 
"Other";
}

/*
 * We have 3 options:
 * - For FF and Opera, which support RFC 2231, use that format.
 * - For IE and Chrome, use attwithfnrawpctenclong
 *   (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
 * - For the others, convert to ISO-8859-1, if possible
 */
$formatRFC2231 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef 'Content-Disposition: attachment; filename="%s"';

switch (
detectUserAgent()) {
    case 
"Opera":
    case 
"Firefox":
        
$orfilename rawurlencode($orfilename);
        
$format $formatRFC2231;
        break;

    case 
"IE":
    case 
"Chrome":
        
$orfilename rawurlencode($orfilename);
        
$format $formatDef;
        break;
    default:
        if (
function_exists('iconv'))
            
$orfilename =
                @
iconv("UTF-8""ISO-8859-1//TRANSLIT"$orfilename);
        
$format $formatDef;
}

header(sprintf($format$orfilename));
//cannot send error messages from now on (headers already sent)

//replace by real content type, perhaps infering from the file extension
$contentType "application/octet-stream";
header("Content-Type: $contentType");

header("Content-Transfer-Encoding: binary");

header("Content-Length: $filesize");

if (
$_SERVER['REQUEST_METHOD'] == "HEAD")
    die();
    
while (!
feof($fp)) {
    
$s = @fread($fp8192);
    if (
$s === false)
        break; 
//useless to send error messages
  
    
echo $s;
}
?>

This example opens a RAR file and presents the requested file inside the RAR archive for download to the client.

Przykład #2 RAR extension filesystem extraction example

<?php

$rar_file 
rar_open('example.rar') or die("Can't open Rar archive");

$entries rar_list($rar_file);

foreach (
$entries as $entry) {
    echo 
'Filename: ' $entry->getName() . "\n";
    echo 
'Packed size: ' $entry->getPackedSize() . "\n";
    echo 
'Unpacked size: ' $entry->getUnpackedSize() . "\n";

    
$entry->extract('/dir/extract/to/');
}

rar_close($rar_file);

?>

This example opens a RAR file archive and extracts each entry to the specified directory.



Rar Funkcje


rar_wrapper_cache_stats

(PECL rar >= 3.0.0)

rar_wrapper_cache_statsCache hits and misses for the URL wrapper

Opis

string rar_wrapper_cache_stats ( void )

Ostrzeżenie

Ta funkcja jest obecnie nieudokumentowana, dostępna jest jedynie lista jej argumentów.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości


Spis treści



The RarArchive class

(No version information available, might only be in SVN)

Wstęp

This class represents a RAR archive, which may be formed by several volumes (parts) and which contains a number of RAR entries (i.e., files, directories and other special objects such as symbolic links).

Objects of this class can be traversed, yielding the entries stored in the respective RAR archive. Those entries can also be obtained through RarArchive::getEntry() and RarArchive::getEntries().

Krótki opis klasy

final RarArchive implements Traversable {
/* Metody */
public bool close ( void )
public string getComment ( void )
public array getEntries ( void )
public RarEntry getEntry ( string $entryname )
public bool isBroken ( void )
public bool isSolid ( void )
public static RarArchive open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )
public bool setAllowBroken ( bool $allow_broken )
public string __toString ( void )
}

RarArchive::close

rar_close

(PECL rar >= 2.0.0)

RarArchive::close -- rar_closeClose RAR archive and free all resources

Opis

Styl obiektowy (method):

public bool RarArchive::close ( void )

Styl proceduralny:

bool rar_close ( RarArchive $rarfile )

Close RAR archive and free all allocated resources.

Parametry

rarfile

A RarArchive object, opened with rar_open().

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja Opis
2.0.0 The RAR entries returned by RarArchive::getEntry() and RarArchive::getEntries() are now invalidated when calling this method. This means that all instance methods called for such entries and not guaranteed to succeed.

Przykłady

Przykład #1 Styl obiektowy

<?php
$rar_arch 
RarArchive::open('latest_winrar.rar');
echo 
$rar_arch."\n";
$rar_arch->close();
echo 
$rar_arch."\n";
?>

Powyższy przykład wyświetli coś podobnego do:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

Przykład #2 Styl proceduralny

<?php
$rar_arch 
rar_open('latest_winrar.rar');
echo 
$rar_arch."\n";
rar_close($rar_arch);
echo 
$rar_arch."\n";
?>



RarArchive::getComment

rar_comment_get

(PECL rar >= 2.0.0)

RarArchive::getComment -- rar_comment_getGet comment text from the RAR archive

Opis

Styl obiektowy (method):

public string RarArchive::getComment ( void )

Styl proceduralny:

string rar_comment_get ( RarArchive $rarfile )

Get the (global) comment stored in the RAR archive. It may be up to 64 KiB long.

Informacja:

This extension does not support comments at the entry level.

Parametry

rarfile

A RarArchive object, opened with rar_open().

Zwracane wartości

Returns the comment or NULL if there is none.

Informacja:

RAR has currently no support for unicode comments. The encoding of the result of this function is not specified, but it will probably be Windows-1252.

Przykłady

Przykład #1 Styl obiektowy

<?php
$rar_arch 
RarArchive::open('commented.rar'); 
echo 
$rar_arch->getComment();
?>

Powyższy przykład wyświetli coś podobnego do:

This is the comment of the file commented.rar.

Przykład #2 Styl proceduralny

<?php
$rar_arch 
rar_open('commented.rar'); 
echo 
rar_comment_get($rar_arch);
?>



RarArchive::getEntries

rar_list

(PECL rar >= 2.0.0)

RarArchive::getEntries -- rar_listGet full list of entries from the RAR archive

Opis

Styl obiektowy (method):

public array RarArchive::getEntries ( void )

Styl proceduralny:

array rar_list ( RarArchive $rarfile )

Get entries list (files and directories) from the RAR archive.

Informacja:

If the archive has entries with the same name, this method, together with RarArchive foreach iteration and array-like access with numeric indexes, are the only ones to access all the entries (i.e., RarArchive::getEntry() and the rar:// wrapper are insufficient).

Parametry

rarfile

A RarArchive object, opened with rar_open().

Zwracane wartości

rar_list() returns array of RarEntry objects lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
3.0.0 Support for RAR archives with repeated entry names is no longer defective.

Przykłady

Przykład #1 Styl obiektowy

<?php
$rar_arch 
RarArchive::open('solid.rar');
if (
$rar_arch === FALSE)
    die(
"Could not open RAR archive.");

$rar_entries $rar_arch->getEntries();
if (
$rar_entries === FALSE)
    die(
"Could retrieve entries.");

echo 
"Found " count($rar_entries) . " entries.\n";

foreach (
$rar_entries as $e) {
    echo 
$e;
    echo 
"\n";
}
$rar_arch->close();
?>

Powyższy przykład wyświetli coś podobnego do:

Found 2 entries.
RarEntry for file "tese.txt" (23b93a7a)
RarEntry for file "unrardll.txt" (2ed64b6e)

Przykład #2 Styl proceduralny

<?php
$rar_arch 
rar_open('solid.rar');
if (
$rar_arch === FALSE)
    die(
"Could not open RAR archive.");

$rar_entries rar_list($rar_arch);
if (
$rar_entries === FALSE)
    die(
"Could retrieve entries.");

echo 
"Found " count($rar_entries) . " entries.\n";

foreach (
$rar_entries as $e) {
    echo 
$e;
    echo 
"\n";
}
rar_close($rar_arch);
?>

Zobacz też:



RarArchive::getEntry

rar_entry_get

(PECL rar >= 2.0.0)

RarArchive::getEntry -- rar_entry_getGet entry object from the RAR archive

Opis

Styl obiektowy (method):

public RarEntry RarArchive::getEntry ( string $entryname )

Styl proceduralny:

RarEntry rar_entry_get ( RarArchive $rarfile , string $entryname )

Get entry object (file or directory) from the RAR archive.

Informacja:

You can also get entry objects using RarArchive::getEntries().

Note that a RAR archive can have multiple entries with the same name; this method will retrieve only the first.

Parametry

rarfile

A RarArchive object, opened with rar_open().

entryname

Path to the entry within the RAR archive.

Informacja:

The path must be the same returned by RarEntry::getName().

Zwracane wartości

Returns the matching RarEntry object lub FALSE w przypadku niepowodzenia.

Przykłady

Przykład #1 Styl obiektowy

<?php
$rar_arch 
RarArchive::open('solid.rar');
if (
$rar_arch === FALSE)
    die(
"Could not open RAR archive.");
$rar_entry $rar_arch->getEntry('tese.txt');
if (
$rar_entry === FALSE)
    die(
"Could get such entry");
echo 
get_class($rar_entry)."\n";
echo 
$rar_entry;
$rar_arch->close();
?>

Powyższy przykład wyświetli coś podobnego do:

RarEntry
RarEntry for file "tese.txt" (23b93a7a)

Przykład #2 Styl proceduralny

<?php
$rar_arch 
rar_open('solid.rar');
if (
$rar_arch === FALSE)
    die(
"Could not open RAR archive.");
$rar_entry rar_entry_get($rar_arch'tese.txt');
if (
$rar_entry === FALSE)
    die(
"Could get such entry");
echo 
get_class($rar_entry)."\n";
echo 
$rar_entry;
rar_close($rar_arch);
?>

Zobacz też:



RarArchive::isBroken

rar_broken_is

(PECL rar >= 3.0.0)

RarArchive::isBroken -- rar_broken_isTest whether an archive is broken (incomplete)

Opis

Styl obiektowy (method):

public bool RarArchive::isBroken ( void )

Styl proceduralny:

bool rar_broken_is ( RarArchive $rarfile )

This function determines whether an archive is incomplete, i.e., if a volume is missing or a volume is truncated.

Parametry

rarfile

A RarArchive object, opened with rar_open().

Zwracane wartości

Returns TRUE if the archive is broken, FALSE otherwise. This function may also return FALSE if the passed file has already been closed. The only way to tell the two cases apart is to enable exceptions with RarException::setUsingExceptions(); however, this should be unnecessary as a program should not operate on closed files.

Przykłady

Przykład #1 Styl obiektowy

<?php
function retnull() { return null; }
$file dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch RarArchive::open($filenull'retnull');
var_dump($arch->isBroken());
?>

Powyższy przykład wyświetli coś podobnego do:

bool(true)

Przykład #2 Styl proceduralny

<?php
function retnull() { return null; }
$file dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch rar_open($filenull'retnull');
var_dump(rar_broken_is($arch));
?>

Zobacz też:



RarArchive::isSolid

rar_solid_is

(PECL rar >= 2.0.0)

RarArchive::isSolid -- rar_solid_isCheck whether the RAR archive is solid

Opis

Styl obiektowy (method):

public bool RarArchive::isSolid ( void )

Styl proceduralny:

bool rar_solid_is ( RarArchive $rarfile )

Check whether the RAR archive is solid. Individual file extraction is slower on solid archives.

Parametry

rarfile

A RarArchive object, opened with rar_open().

Zwracane wartości

Returns TRUE if the archive is solid, FALSE otherwise.

Przykłady

Przykład #1 Styl obiektowy

<?php
$arch1 
RarArchive::open("store_method.rar");
$arch2 RarArchive::open("solid.rar");
echo 
"$arch1: " . ($arch1->isSolid()?'yes':'no') ."\n";
echo 
"$arch2: " . ($arch2->isSolid()?'yes':'no') . "\n";
?>

Powyższy przykład wyświetli coś podobnego do:

RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes

Przykład #2 Styl proceduralny

<?php
$arch1 
rar_open("store_method.rar");
$arch2 rar_open("solid.rar");
echo 
"$arch1: " . (rar_solid_is($arch1)?'yes':'no') ."\n";
echo 
"$arch2: " . (rar_solid_is($arch2)?'yes':'no') . "\n";
?>



RarArchive::open

rar_open

(PECL rar >= 2.0.0)

RarArchive::open -- rar_openOpen RAR archive

Opis

Styl obiektowy (method):

public static RarArchive RarArchive::open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )

Styl proceduralny:

RarArchive rar_open ( string $filename [, string $password = NULL [, callable $volume_callback = NULL ]] )

Open specified RAR archive and return RarArchive instance representing it.

Informacja:

If opening a multi-volume archive, the path of the first volume should be passed as the first parameter. Otherwise, not all files will be shown. This is by design.

Parametry

filename

Path to the Rar archive.

password

A plain password, if needed to decrypt the headers. It will also be used by default if encrypted files are found. Note that the files may have different passwords in respect to the headers and among them.

volume_callback

A function that receives one parameter – the path of the volume that was not found – and returns a string with the correct path for such volume or NULL if such volume does not exist or is not known. The programmer should ensure the passed function doesn't cause loops as this function is called repeatedly if the path returned in a previous call did not correspond to the needed volume. Specifying this parameter omits the notice that would otherwise be emitted whenever a volume is not found; an implementation that only returns NULL can therefore be used to merely omit such notices.

Ostrzeżenie

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Zwracane wartości

Returns the requested RarArchive instance lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
3.0.0 volume_callback was added.

Przykłady

Przykład #1 Styl obiektowy

<?php
$rar_arch 
RarArchive::open('encrypted_headers.rar''samplepassword');
if (
$rar_arch === FALSE)
    die(
"Failed opening file");
    
$entries $rar_arch->getEntries();
if (
$entries === FALSE)
    die(
"Failed fetching entries");

echo 
"Found " count($entries) . " files.\n";

if (empty(
$entries))
    die(
"No valid entries found.");
    
$stream reset($entries)->getStream();
if (
$stream === FALSE)
    die(
"Failed opening first file");

$rar_arch->close();

echo 
"Content of first one follows:\n";
echo 
stream_get_contents($stream);

fclose($stream);
?>

Powyższy przykład wyświetli coś podobnego do:

Found 2 files.
Content of first one follows:
Encrypted file 1 contents.

Przykład #2 Styl proceduralny

<?php
$rar_arch 
rar_open('encrypted_headers.rar''samplepassword');
if (
$rar_arch === FALSE)
    die(
"Failed opening file");
    
$entries rar_list($rar_arch);
if (
$entries === FALSE)
    die(
"Failed fetching entries");

echo 
"Found " count($entries) . " files.\n";

if (empty(
$entries))
    die(
"No valid entries found.");
    
$stream reset($entries)->getStream();
if (
$stream === FALSE)
    die(
"Failed opening first file");

rar_close($rar_arch);

echo 
"Content of first one follows:\n";
echo 
stream_get_contents($stream);

fclose($stream);
?>

Przykład #3 Volume Callback

<?php
/* In this example, there's a volume named multi_broken.part1.rar
 * whose next volume is named multi.part2.rar */
function resolve($vol) {
    if (
preg_match('/_broken/'$vol))
        return 
str_replace('_broken'''$vol);
    else
        return 
null;
}
$rar_file1 rar_open(dirname(__FILE__).'/multi_broken.part1.rar'null'resolve');
$entry $rar_file1->getEntry('file2.txt');
$entry->extract(nulldirname(__FILE__) . "/temp_file2.txt");
?>

Zobacz też:



RarArchive::setAllowBroken

(PECL rar >= 3.0.0)

RarArchive::setAllowBrokenWhether opening broken archives is allowed

Opis

Styl obiektowy (method):

public bool RarArchive::setAllowBroken ( bool $allow_broken )

Styl proceduralny:

bool rar_allow_broken_set ( RarArchive $rarfile , bool $allow_broken )

This method defines whether broken archives can be read or all the operations that attempt to extract the archive entries will fail. Broken archives are archives for which no error is detected when the file is opened but an error occurs when reading the entries.

Parametry

rarfile

A RarArchive object, opened with rar_open().

allow_broken

Whether to allow reading broken files (TRUE) or not (FALSE).

Zwracane wartości

Returns TRUE lub FALSE w przypadku niepowodzenia. It will only fail if the file has already been closed.

Przykłady

Przykład #1 Styl obiektowy

<?php
function retnull() { return null; }
$file dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a RarArchive::open($filenull'retnull');
$a->setAllowBroken(true);
foreach (
$a->getEntries() as $e) {
    echo 
"$e\n";
}
var_dump(count($a));
?>

Powyższy przykład wyświetli coś podobnego do:

RarEntry for file "file1.txt" (52b28202)
int(1)

Przykład #2 Styl proceduralny

<?php
function retnull() { return null; }
$file dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a rar_open($filenull'retnull');
rar_allow_broken_set($atrue);
foreach (
rar_list($a) as $e) {
    echo 
"$e\n";
}
var_dump(count($a));
?>

Zobacz też:



RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toStringGet text representation

Opis

public string RarArchive::__toString ( void )

Provides a string representation for this RarArchive object. It currently shows the full path name of the archive volume that was opened and whether the resource is valid or was already closed through a call to RarArchive::close().

This method may be used only for debugging purposes, as there are no guarantees as to which information the result contains or how it is formatted.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A textual representation of this RarArchive object. The content of this representation is unspecified.

Przykłady

Przykład #1 RarArchive::__toString() example

<?php
$rar_arch 
RarArchive::open('latest_winrar.rar');
echo 
$rar_arch."\n";
$rar_arch->close();
echo 
$rar_arch."\n";
?>

Powyższy przykład wyświetli coś podobnego do:

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)


Spis treści



The RarEntry class

(No version information available, might only be in SVN)

Wstęp

A RAR entry, representing a directory or a compressed file inside a RAR archive.

Krótki opis klasy

final RarEntry {
/* Stałe */
const integer HOST_MSDOS = 0 ;
const integer HOST_OS2 = 1 ;
const integer HOST_WIN32 = 2 ;
const integer HOST_UNIX = 3 ;
const integer HOST_MACOS = 4 ;
const integer HOST_BEOS = 5 ;
const integer ATTRIBUTE_WIN_READONLY = 1 ;
const integer ATTRIBUTE_WIN_HIDDEN = 2 ;
const integer ATTRIBUTE_WIN_SYSTEM = 4 ;
const integer ATTRIBUTE_WIN_DIRECTORY = 16 ;
const integer ATTRIBUTE_WIN_ARCHIVE = 32 ;
const integer ATTRIBUTE_WIN_DEVICE = 64 ;
const integer ATTRIBUTE_WIN_NORMAL = 128 ;
const integer ATTRIBUTE_WIN_TEMPORARY = 256 ;
const integer ATTRIBUTE_WIN_SPARSE_FILE = 512 ;
const integer ATTRIBUTE_WIN_REPARSE_POINT = 1024 ;
const integer ATTRIBUTE_WIN_COMPRESSED = 2048 ;
const integer ATTRIBUTE_WIN_OFFLINE = 4096 ;
const integer ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192 ;
const integer ATTRIBUTE_WIN_ENCRYPTED = 16384 ;
const integer ATTRIBUTE_WIN_VIRTUAL = 65536 ;
const integer ATTRIBUTE_UNIX_WORLD_EXECUTE = 1 ;
const integer ATTRIBUTE_UNIX_WORLD_WRITE = 2 ;
const integer ATTRIBUTE_UNIX_WORLD_READ = 4 ;
const integer ATTRIBUTE_UNIX_GROUP_EXECUTE = 8 ;
const integer ATTRIBUTE_UNIX_GROUP_WRITE = 16 ;
const integer ATTRIBUTE_UNIX_GROUP_READ = 32 ;
const integer ATTRIBUTE_UNIX_OWNER_EXECUTE = 64 ;
const integer ATTRIBUTE_UNIX_OWNER_WRITE = 128 ;
const integer ATTRIBUTE_UNIX_OWNER_READ = 256 ;
const integer ATTRIBUTE_UNIX_STICKY = 512 ;
const integer ATTRIBUTE_UNIX_SETGID = 1024 ;
const integer ATTRIBUTE_UNIX_SETUID = 2048 ;
const integer ATTRIBUTE_UNIX_FINAL_QUARTET = 61440 ;
const integer ATTRIBUTE_UNIX_FIFO = 4096 ;
const integer ATTRIBUTE_UNIX_CHAR_DEV = 8192 ;
const integer ATTRIBUTE_UNIX_DIRECTORY = 16384 ;
const integer ATTRIBUTE_UNIX_BLOCK_DEV = 24576 ;
const integer ATTRIBUTE_UNIX_REGULAR_FILE = 32768 ;
const integer ATTRIBUTE_UNIX_SYM_LINK = 40960 ;
const integer ATTRIBUTE_UNIX_SOCKET = 49152 ;
/* Metody */
public bool extract ( string $dir [, string $filepath = '' [, string $password = NULL [, bool $extended_data = false ]]] )
public int getAttr ( void )
public string getCrc ( void )
public string getFileTime ( void )
public int getHostOs ( void )
public int getMethod ( void )
public string getName ( void )
public int getPackedSize ( void )
public resource getStream ([ string $password ] )
public int getUnpackedSize ( void )
public int getVersion ( void )
public bool isDirectory ( void )
public bool isEncrypted ( void )
public string __toString ( void )
}

Stałe predefiniowane

RarEntry::HOST_MSDOS

If the return value of RarEntry::getHostOs() equals this constant, MS-DOS was used to add this entry. Use instead of RAR_HOST_MSDOS.

RarEntry::HOST_OS2

If the return value of RarEntry::getHostOs() equals this constant, OS/2 was used to add this entry. Intended to replace RAR_HOST_OS2.

RarEntry::HOST_WIN32

If the return value of RarEntry::getHostOs() equals this constant, Microsoft Windows was used to add this entry. Intended to replace RAR_HOST_WIN32.

RarEntry::HOST_UNIX

If the return value of RarEntry::getHostOs() equals this constant, an unspecified UNIX OS was used to add this entry. Intended to replace RAR_HOST_UNIX.

RarEntry::HOST_MACOS

If the return value of RarEntry::getHostOs() equals this constant, Mac OS was used to add this entry.

RarEntry::HOST_BEOS

If the return value of RarEntry::getHostOs() equals this constant, BeOS was used to add this entry. Intended to replace RAR_HOST_BEOS.

RarEntry::ATTRIBUTE_WIN_READONLY

Bit that represents a Windows entry with a read-only attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_HIDDEN

Bit that represents a Windows entry with a hidden attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SYSTEM

Bit that represents a Windows entry with a system attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DIRECTORY

Bit that represents a Windows entry with a directory attribute (entry is a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_ARCHIVE

Bit that represents a Windows entry with an archive attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DEVICE

Bit that represents a Windows entry with a device attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NORMAL

Bit that represents a Windows entry with a normal file attribute (entry is NOT a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_TEMPORARY

Bit that represents a Windows entry with a temporary attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SPARSE_FILE

Bit that represents a Windows entry with a sparse file attribute (file is an NTFS sparse file). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_REPARSE_POINT

Bit that represents a Windows entry with a reparse point attribute (entry is an NTFS reparse point, e.g. a directory junction or a mount file system). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_COMPRESSED

Bit that represents a Windows entry with a compressed attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_OFFLINE

Bit that represents a Windows entry with an offline attribute (entry is offline and not accessible). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED

Bit that represents a Windows entry with a not content indexed attribute (entry is to be indexed). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_ENCRYPTED

Bit that represents a Windows entry with an encrypted attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_VIRTUAL

Bit that represents a Windows entry with a virtual attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE

Bit that represents a UNIX entry that is world executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE

Bit that represents a UNIX entry that is world writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_READ

Bit that represents a UNIX entry that is world readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE

Bit that represents a UNIX entry that is group executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE

Bit that represents a UNIX entry that is group writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_READ

Bit that represents a UNIX entry that is group readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE

Bit that represents a UNIX entry that is owner executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE

Bit that represents a UNIX entry that is owner writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_READ

Bit that represents a UNIX entry that is owner readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_STICKY

Bit that represents the UNIX sticky bit. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETGID

Bit that represents the UNIX setgid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETUID

Bit that represents the UNIX setuid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET

Mask to isolate the last four bits (nibble) of UNIX attributes (_S_IFMT, the type of file mask). To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constants RarEntry::ATTRIBUTE_UNIX_FIFO, RarEntry::ATTRIBUTE_UNIX_CHAR_DEV, RarEntry::ATTRIBUTE_UNIX_DIRECTORY, RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV, RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE, RarEntry::ATTRIBUTE_UNIX_SYM_LINK and RarEntry::ATTRIBUTE_UNIX_SOCKET.

RarEntry::ATTRIBUTE_UNIX_FIFO

Unix FIFOs will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_CHAR_DEV

Unix character devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_DIRECTORY

Unix directories will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV

Unix block devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE

Unix regular files (not directories) will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.

Unix symbolic links will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_SOCKET

Unix sockets will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.


RarEntry::extract

(PECL rar >= 0.1)

RarEntry::extractExtract entry from the archive

Opis

public bool RarEntry::extract ( string $dir [, string $filepath = '' [, string $password = NULL [, bool $extended_data = false ]]] )

RarEntry::extract() extracts the entry's data. It will create new file in the specified dir with the name identical to the entry's name, unless the second argument is specified. See below for more information.

Parametry

dir

Path to the directory where files should be extracted. This parameter is considered if and only if filepath is not. If both parameters are empty an extraction to the current directory will be attempted.

filepath

Path (relative or absolute) containing the directory and filename of the extracted file. This parameter overrides both the parameter dir and the original file name.

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), CRC checking will fail and this method will fail and return FALSE. If no password is given and one is required, this method will fail and return FALSE. You can check whether an entry is encrypted with RarEntry::isEncrypted().

extended_data

If TRUE, extended information such as NTFS ACLs and Unix owner information will be set in the extract files, as long as it's present in the archive.

Ostrzeżenie

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Rejestr zmian

Wersja Opis
3.0.0 extended_data was added.
3.0.0 Support for RAR archives with repeated entry names is no longer defective.

Przykłady

Przykład #1 RarEntry::extract() example

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

$entry->extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false'/dir/to/new_name.txt'); // create /dir/to/new_name.txt

?>

Przykład #2 How to extract all files in archive:

<?php

/* example by Erik Jenssen aka erix */

$filename "foobar.rar";
$filepath "/home/foo/bar/";

$rar_file rar_open($filepath.$filename);
$list rar_list($rar_file);
foreach(
$list as $file) {
    
$entry rar_entry_get($rar_file$file);
    
$entry->extract("."); // extract to the current dir
}
rar_close($rar_file);

?>

Zobacz też:



RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttrGet attributes of the entry

Opis

public int RarEntry::getAttr ( void )

Returns the OS-dependent attributes of the archive entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the attributes or FALSE on error.

Przykłady

Przykład #1 RarEntry::getAttr() example

<?php

$rar_file 
rar_open('example.rar') or die("Can't open Rar archive");

$entry rar_entry_get($rar_file'dir/in/the/archive') or die("Can't find such entry");

$host_os $entry->getHostOs();
$attr $entry->getAttr();

switch(
$host_os) {
    case 
RAR_HOST_MSDOS:
    case 
RAR_HOST_OS2:
    case 
RAR_HOST_WIN32:
    case 
RAR_HOST_MACOS:
        
printf("%c%c%c%c%c%c\n",
                (
$attr 0x08) ? 'V' '.',
                (
$attr 0x10) ? 'D' '.',
                (
$attr 0x01) ? 'R' '.',
                (
$attr 0x02) ? 'H' '.',
                (
$attr 0x04) ? 'S' '.',
                (
$attr 0x20) ? 'A' '.');
        break;
    case 
RAR_HOST_UNIX:
    case 
RAR_HOST_BEOS:
        switch (
$attr 0xF000)
        {
            case 
0x4000:
                
printf("d");
                break;
            case 
0xA000:
                
printf("l");
                break;
            default:
                
printf("-");
                break;
        }
        
printf("%c%c%c%c%c%c%c%c%c\n",
                (
$attr 0x0100) ? 'r' '-',
                (
$attr 0x0080) ? 'w' '-',
                (
$attr 0x0040) ? (($attr 0x0800) ? 's':'x'):(($attr 0x0800) ? 'S':'-'),
                (
$attr 0x0020) ? 'r' '-',
                (
$attr 0x0010) ? 'w' '-',
                (
$attr 0x0008) ? (($attr 0x0400) ? 's':'x'):(($attr 0x0400) ? 'S':'-'),
                (
$attr 0x0004) ? 'r' '-',
                (
$attr 0x0002) ? 'w' '-',
                (
$attr 0x0001) ? 'x' '-');
        break;
}

rar_close($rar_file);

?>

Zobacz też:



RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrcGet CRC of the entry

Opis

public string RarEntry::getCrc ( void )

Returns an hexadecimal string representation of the CRC of the archive entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the CRC of the archive entry or FALSE on error.

Rejestr zmian

Wersja Opis
2.0.0 This method now returns correct values for multiple volume archives.



RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTimeGet entry last modification time

Opis

public string RarEntry::getFileTime ( void )

Gets entry last modification time.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns entry last modification time as string in format YYYY-MM-DD HH:II:SS, or FALSE on error.



RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOsGet entry host OS

Opis

public int RarEntry::getHostOs ( void )

Returns the code of the host OS of the archive entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the code of the host OS, or FALSE on error.

Przykłady

Przykład #1 RarEntry::getHostOs() example (version >= 2.0.0)

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

switch (
$entry->getHostOs()) {
    case 
RarEntry::HOST_MSDOS:
        echo 
"MS-DOS\n";
        break;
    case 
RarEntry::HOST_OS2:
        echo 
"OS2\n";
        break;
    case 
RarEntry::HOST_WIN32:
        echo 
"Win32\n";
        break;
    case 
RarEntry::HOST_MACOS:
        echo 
"MacOS\n";
        break;
    case 
RarEntry::HOST_UNIX:
        echo 
"Unix/Linux\n";
        break;
    case 
RarEntry::HOST_BEOS:
        echo 
"BeOS\n";
        break;
}

?>

Przykład #2 RarEntry::getHostOs() example (version <= 1.0.0)

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

switch (
$entry->getHostOs()) {
    case 
RAR_HOST_MSDOS:
        echo 
"MS-DOS\n";
        break;
    case 
RAR_HOST_OS2:
        echo 
"OS2\n";
        break;
    case 
RAR_HOST_WIN32:
        echo 
"Win32\n";
        break;
    case 
RAR_HOST_MACOS:
        echo 
"MacOS\n";
        break;
    case 
RAR_HOST_UNIX:
        echo 
"Unix/Linux\n";
        break;
    case 
RAR_HOST_BEOS:
        echo 
"BeOS\n";
        break;
}

?>

Zobacz też:



RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethodGet pack method of the entry

Opis

public int RarEntry::getMethod ( void )

RarEntry::getMethod() returns number of the method used when adding current archive entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the method number or FALSE on error.

Przykłady

Przykład #1 RarEntry::getMethod() example

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

echo 
"Method number: " $entry->getMethod();

?>



RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getNameGet name of the entry

Opis

public string RarEntry::getName ( void )

Returns the name (with path) of the archive entry.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the entry name as a string, or FALSE on error.

Rejestr zmian

Wersja Opis
2.0.0 As of version 2.0.0, the returned string is encoded in Unicode/UTF-8.

Przykłady

Przykład #1 RarEntry::getName() example

<?php

//this example is safe even in pages not encoded in UTF-8
//for those encoded in UTF-8, the call to mb_convert_encoding is unnecessary

$rar_file rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

echo 
"Entry name: " mb_convert_encoding(
    
htmlentities(
        
$entry->getName(),
        
ENT_COMPAT,
        
"UTF-8"
    
),
    
"HTML-ENTITIES",
    
"UTF-8"
);

?>



RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSizeGet packed size of the entry

Opis

public int RarEntry::getPackedSize ( void )

Get packed size of the archive entry.

Informacja:

Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the packed size, or FALSE on error.

Rejestr zmian

Wersja Opis
2.0.0 This method now returns correct values of packed sizes bigger than 2 GiB on platforms with 64-bit integers and never returns negative values on other platforms.

Przykłady

Przykład #1 RarEntry::getPackedSize() example

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

echo 
"Packed size of " $entry->getName() . " = " $entry->getPackedSize() . " bytes";

?>



RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStreamGet file handler for entry

Opis

public resource RarEntry::getStream ([ string $password ] )

Returns a file handler that supports read operations. This handler provides on-the-fly decompression for this entry.

The handler is not invalidated by calling rar_close().

Ostrzeżenie

The resulting stream has no integrity verification. In particular, file corruption and decryption with a wrong a key will not be detected. It is the programmer's responsability to use the entry's CRC to check for integrity, if he so wishes.

Parametry

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), this method's resulting stream will produce wrong output. If no password is given and one is required, this method will fail and return FALSE. You can check whether an entry is encrypted with RarEntry::isEncrypted().

Zwracane wartości

The file handler lub FALSE w przypadku niepowodzenia.

Rejestr zmian

Wersja Opis
3.0.0 Support for RAR archives with repeated entry names is no longer defective.

Przykłady

Przykład #1 RarEntry::getStream() example

<?php

$rar_file 
rar_open('example.rar');
if (
$rar_file === false)
    die(
"Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt');
if (
$entry === false)
    die(
"Failed to find such entry");

$stream $entry->getStream();
if (
$stream === false)
    die(
"Failed to obtain stream.");

rar_close($rar_file); //stream is independent from file

while (!feof($stream)) {
    
$buff fread($stream8192);
    if (
$buff !== false)
        echo 
$buff;
    else
        break; 
//fread error
}

fclose($stream);

?>

Zobacz też:



RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSizeGet unpacked size of the entry

Opis

public int RarEntry::getUnpackedSize ( void )

Get unpacked size of the archive entry.

Informacja:

Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the unpacked size, or FALSE on error.

Rejestr zmian

Wersja Opis
2.0.0 This method now returns correct values of unpacked sizes bigger than 2 GiB on platforms with 64-bit integers and never returns negative values on other platforms.

Zwracane wartości

Przykład #1 RarEntry::getUnpackedSize() example

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

echo 
"Unpacked size of " $entry->getName() . " = " $entry->getPackedSize() . " bytes";

?>



RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersionGet minimum version of RAR program required to unpack the entry

Opis

public int RarEntry::getVersion ( void )

Returns minimum version of RAR program (e.g. WinRAR) required to unpack the entry. It is encoded as 10 * major version + minor version.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns the version or FALSE on error.

Przykłady

Przykład #1 RarEntry::getVersion() example

<?php

$rar_file 
rar_open('example.rar') or die("Failed to open Rar archive");

$entry rar_entry_get($rar_file'Dir/file.txt') or die("Failed to find such entry");

echo 
"Rar version required for unpacking: " $entry->getVersion();

?>



RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectoryTest whether an entry represents a directory

Opis

public bool RarEntry::isDirectory ( void )

Tests whether the current entry is a directory.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if this entry is a directory and FALSE otherwise.

Notatki

This function is only available starting with version 2.0.0, but one can also test whether an entry is a directory by checking the entry attributes, like this (only works for files compressed in RAR for Windows or Unix):

<?php
//...
//Open file, get entry and store in variable $e...
//...

$isDirectory = (bool) ((($e->getHostOs() == RAR_HOST_WIN32) && ($e->getAttr() & 0x10)) ||
    ((
$e->getHostOs() == RAR_HOST_UNIX) && (($e->getAttr() & 0xf000) == 0x4000)));
?>



RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncryptedTest whether an entry is encrypted

Opis

public bool RarEntry::isEncrypted ( void )

Tests whether the current entry contents are encrypted.

Informacja:

The password used may differ between files inside the same RAR archive.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if the current entry is encrypted and FALSE otherwise.



RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toStringGet text representation of entry

Opis

public string RarEntry::__toString ( void )

RarEntry::__toString() returns a textual representation for this entry. It includes whether the entry is a file or a directory (symbolic links and other special objects will be treated as files), the UTF-8 name of the entry and its CRC. The form and content of this representation may be changed in the future, so they cannot be relied upon.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

A textual representation for the entry.


Spis treści



The RarException class

(No version information available, might only be in SVN)

Wstęp

This class serves two purposes: it is the type of the exceptions thrown by the RAR extension functions and methods and it allows, through static methods to query and define the error behaviour of the extension, i.e., whether exceptions are thrown or only warnings are emitted.

The following error codes are used:

  • -1 - error outside UnRAR library
  • 11 - insufficient memory
  • 12 - bad data
  • 13 - bad archive
  • 14 - unknown format
  • 15 - file open error
  • 16 - file create error
  • 17 - file close error
  • 18 - read error
  • 19 - write error
  • 20 - buffer too small
  • 21 - unkown RAR error
  • 22 - password required but not given

Krótki opis klasy

final RarException extends Exception {
/* Metody */
public static bool isUsingExceptions ( void )
public static void setUsingExceptions ( bool $using_exceptions )
/* Metody dziedziczone */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public mixed 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 )
}

RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptionsCheck whether error handling with exceptions is in use

Opis

public static bool RarException::isUsingExceptions ( void )

Checks whether the RAR functions will emit warnings and return error values or whether they will throw exceptions in most of the circumstances (does not include some programmatic errors such as passing the wrong type of arguments).

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Returns TRUE if exceptions are being used, FALSE otherwise.

Przykłady

Przykład #1 RarException::isUsingExceptions() example

<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)

Zobacz też:



RarException::setUsingExceptions

(PECL rar >= 2.0.0)

RarException::setUsingExceptionsActivate and deactivate error handling with exceptions

Opis

public static void RarException::setUsingExceptions ( bool $using_exceptions )

If and only if the argument is TRUE, then, instead of emitting warnings and returning a special value indicating error when the UnRAR library encounters an error, an exception of type RarException will be thrown.

Exceptions will also be thrown for the following errors, which occur outside the library (their error code will be -1):

Parametry

using_exceptions

Should be TRUE to activate exception throwing, FALSE to deactivate (the default).

Przykłady

Przykład #1 RarException::setUsingExceptions() example

<?php
var_dump
(RarException::isUsingExceptions());
$arch RarArchive::open("does_not_exist.rar");
var_dump($arch);

RarException::setUsingExceptions(true);
var_dump(RarException::isUsingExceptions());
$arch RarArchive::open("does_not_exist.rar");
var_dump($arch); //not reached
?>

Powyższy przykład wyświetli coś podobnego do:

bool(false)

Warning: RarArchive::open(): Failed to open does_not_exist.rar: ERAR_EOPEN (file open error) in C:\php_rar\trunk\tests\test.php on line 3
bool(false)
bool(true)

Fatal error: Uncaught exception 'RarException' with message 'unRAR internal error: Failed to open does_not_exist.rar: ERAR_EOPEN (file open error)' in C:\php_rar\trunk\tests\test.php:8
Stack trace:
#0 C:\php_rar\trunk\tests\test.php(8): RarArchive::open('does_not_exist....')
#1 {main}
  thrown in C:\php_rar\trunk\tests\test.php on line 8

Zobacz też:


Spis treści




Zip


Wstęp

This extension enables you to transparently read or write ZIP compressed archives and the files inside them.



Instalacja/Konfiguracja

Spis treści


Wymagania

PHP 4

The bundled PHP 4 version requires » ZZIPlib, by Guido Draheim, version 0.10.6 or later

PHP 5.2.0 or later

This extension uses the functions of » zlib by Jean-loup Gailly and Mark Adler.



Instalacja

PHP 4

Informacja:

Zip support before PHP 4.1.0 is experimental.

Ostrzeżenie

Because the PHP 4 zip extension is unmaintained we recommend that the PECL extension is used rather than the bundled one.

Linux systems

In order to use these functions you must compile PHP with zip support by using the --with-zip[=DIR] configure option, where [DIR] is the prefix of the » ZZIPlib library install.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

PHP 5.2.0 and later

Linux systems

In order to use these functions you must compile PHP with zip support by using the --enable-zip configure option.

Windows

Windows users need to enable php_zip.dll inside of php.ini in order to use these functions.

Installation via PECL

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/zip.

DLL z tym rozszerzeniem PECL można pobrać zarówno ze strony » PHP Downloads lub z » http://pecl4win.php.net/

W PHP 4 ten DLL znajduje się w podkatalogu extensions/ binarnej dystrybucji PHP dla Windows.



Konfiguracja wykonawcza

To rozszerzenie nie definiuje posiada żadnych dyrektyw konfiguracyjnych w pliku php.ini.



Typy zasobów

There are two resource types used in the Zip module. The first one is the Zip directory for the Zip archive, the second Zip Entry for the archive entries.




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.

ZipArchive uses class constants. There are three types of constants : Flags (prefixed with FL_), errors (prefixed with ER_) and mode (no prefix).

ZIPARCHIVE::CREATE (integer)
Create the archive if it does not exist.
ZIPARCHIVE::OVERWRITE (integer)
Always start a new archive, this mode will overwrite the file if it already exists.
ZIPARCHIVE::EXCL (integer)
Error if archive already exists.
ZIPARCHIVE::CHECKCONS (integer)
Perform additional consistency checks on the archive, and error if they fail.
ZIPARCHIVE::FL_NOCASE (integer)
Ignore case on name lookup
ZIPARCHIVE::FL_NODIR (integer)
Ignore directory component
ZIPARCHIVE::FL_COMPRESSED (integer)
Read compressed data
ZIPARCHIVE::FL_UNCHANGED (integer)
Use original data, ignoring changes.
ZIPARCHIVE::CM_DEFAULT (integer)
better of deflate or store.
ZIPARCHIVE::CM_STORE (integer)
stored (uncompressed).
ZIPARCHIVE::CM_SHRINK (integer)
shrunk
ZIPARCHIVE::CM_REDUCE_1 (integer)
reduced with factor 1
ZIPARCHIVE::CM_REDUCE_2 (integer)
reduced with factor 2
ZIPARCHIVE::CM_REDUCE_3 (integer)
reduced with factor 3
ZIPARCHIVE::CM_REDUCE_4 (integer)
reduced with factor 4
ZIPARCHIVE::CM_IMPLODE (integer)
imploded
ZIPARCHIVE::CM_DEFLATE (integer)
deflated
ZIPARCHIVE::CM_DEFLATE64 (integer)
deflate64
ZIPARCHIVE::CM_PKWARE_IMPLODE (integer)
PKWARE imploding
ZIPARCHIVE::CM_BZIP2 (integer)
BZIP2 algorithm
ZIPARCHIVE::ER_OK (integer)
No error.
ZIPARCHIVE::ER_MULTIDISK (integer)
Multi-disk zip archives not supported.
ZIPARCHIVE::ER_RENAME (integer)
Renaming temporary file failed.
ZIPARCHIVE::ER_CLOSE (integer)
Closing zip archive failed
ZIPARCHIVE::ER_SEEK (integer)
Seek error
ZIPARCHIVE::ER_READ (integer)
Read error
ZIPARCHIVE::ER_WRITE (integer)
Write error
ZIPARCHIVE::ER_CRC (integer)
CRC error
ZIPARCHIVE::ER_ZIPCLOSED (integer)
Containing zip archive was closed
ZIPARCHIVE::ER_NOENT (integer)
No such file.
ZIPARCHIVE::ER_EXISTS (integer)
File already exists
ZIPARCHIVE::ER_OPEN (integer)
Can't open file
ZIPARCHIVE::ER_TMPOPEN (integer)
Failure to create temporary file.
ZIPARCHIVE::ER_ZLIB (integer)
Zlib error
ZIPARCHIVE::ER_MEMORY (integer)
Memory allocation failure
ZIPARCHIVE::ER_CHANGED (string)
Entry has been changed
ZIPARCHIVE::ER_COMPNOTSUPP (integer)
Compression method not supported.
ZIPARCHIVE::ER_EOF (integer)
Premature EOF
ZIPARCHIVE::ER_INVAL (integer)
Invalid argument
ZIPARCHIVE::ER_NOZIP (integer)
Not a zip archive
ZIPARCHIVE::ER_INTERNAL (integer)
Internal error
ZIPARCHIVE::ER_INCONS (integer)
Zip archive inconsistent
ZIPARCHIVE::ER_REMOVE (integer)
Can't remove file
ZIPARCHIVE::ER_DELETED (integer)
Entry has been deleted


Przykłady

Przykład #1 Create a Zip archive

<?php

$zip 
= new ZipArchive();
$filename "./test112.zip";

if (
$zip->open($filenameZIPARCHIVE::CREATE)!==TRUE) {
    exit(
"cannot open <$filename>\n");
}

$zip->addFromString("testfilephp.txt" time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir "/too.php","/testfromfile.php");
echo 
"numfiles: " $zip->numFiles "\n";
echo 
"status:" $zip->status "\n";
$zip->close();
?>

Przykład #2 Dump the archive details and listing

<?php
$za 
= new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo 
"numFiles: " $za->numFiles "\n";
echo 
"status: " $za->status  "\n";
echo 
"statusSys: " $za->statusSys "\n";
echo 
"filename: " $za->filename "\n";
echo 
"comment: " $za->comment "\n";

for (
$i=0$i<$za->numFiles;$i++) {
    echo 
"index: $i\n";
    
print_r($za->statIndex($i));
}
echo 
"numFile:" $za->numFiles "\n";
?>

Przykład #3 Zip stream wrapper, read an OpenOffice meta info

<?php
$reader 
= new XMLReader();

$reader->open('zip://' dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while (
$reader->read()) {
    if (
$reader->nodeType == XMLREADER::ELEMENT) {
        
$elm $reader->name;
    } else {
        if (
$reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
            break;
        }
        if (!
trim($reader->value)) {
            continue;
        }
        
$odt_meta[$elm] = $reader->value;
    }
}
print_r($odt_meta);
?>

This example uses the old API (PHP 4), it opens a ZIP file archive, reads each file in the archive and prints out its contents. The test2.zip archive used in this example is one of the test archives in the ZZIPlib source distribution.

Przykład #4 Zip Usage Example

<?php

$zip 
zip_open("/tmp/test2.zip");

if (
$zip) {
    while (
$zip_entry zip_read($zip)) {
        echo 
"Name:               " zip_entry_name($zip_entry) . "\n";
        echo 
"Actual Filesize:    " zip_entry_filesize($zip_entry) . "\n";
        echo 
"Compressed Size:    " zip_entry_compressedsize($zip_entry) . "\n";
        echo 
"Compression Method: " zip_entry_compressionmethod($zip_entry) . "\n";

        if (
zip_entry_open($zip$zip_entry"r")) {
            echo 
"File Contents:\n";
            
$buf zip_entry_read($zip_entryzip_entry_filesize($zip_entry));
            echo 
"$buf\n";

            
zip_entry_close($zip_entry);
        }
        echo 
"\n";

    }

    
zip_close($zip);

}
?>


The ZipArchive class

(No version information available, might only be in SVN)

Wstęp

A file archive, compressed with Zip.

Krótki opis klasy

ZipArchive {
/* Właściwości */
/* Metody */
bool addEmptyDir ( string $dirname )
bool addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )
bool addFromString ( string $localname , string $contents )
bool close ( void )
bool deleteIndex ( int $index )
bool deleteName ( string $name )
bool extractTo ( string $destination [, mixed $entries ] )
string getArchiveComment ([ int $flags ] )
string getCommentIndex ( int $index [, int $flags ] )
string getCommentName ( string $name [, int $flags ] )
mixed getFromIndex ( int $index [, int $length = 0 [, int $flags ]] )
mixed getFromName ( string $name [, int $length = 0 [, int $flags ]] )
string getNameIndex ( int $index [, int $flags ] )
string getStatusString ( void )
resource getStream ( string $name )
mixed locateName ( string $name [, int $flags ] )
mixed open ( string $filename [, int $flags ] )
bool renameIndex ( int $index , string $newname )
bool renameName ( string $name , string $newname )
mixed setArchiveComment ( string $comment )
mixed setCommentIndex ( int $index , string $comment )
mixed setCommentName ( string $name , string $comment )
mixed statIndex ( int $index [, int $flags ] )
mixed statName ( name $name [, int $flags ] )
mixed unchangeAll ( void )
mixed unchangeArchive ( void )
mixed unchangeIndex ( int $index )
mixed unchangeName ( string $name )
}

Właściwości

status

Status of the Zip Archive

statusSys

System status of the Zip Archive

numFiles

Number of files in archive

filename

File name in the file system

comment

Comment for the archive


ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PECL zip >= 1.8.0)

ZipArchive::addEmptyDirAdd a new directory

Opis

bool ZipArchive::addEmptyDir ( string $dirname )

Adds an empty directory in the archive.

Parametry

dirname

The directory to add.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Create a new directory in an archive

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    if(
$zip->addEmptyDir('newDirectory')) {
        echo 
'Created a new root directory';
    } else {
        echo 
'Could not create the directory';
    }
    
$zip->close();
} else {
    echo 
'failed';
}
?>


ZipArchive::addFile

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFileAdds a file to a ZIP archive from the given path

Opis

bool ZipArchive::addFile ( string $filename [, string $localname = NULL [, int $start = 0 [, int $length = 0 ]]] )

Adds a file to a ZIP archive from a given path.

Parametry

filename

The path to the file to add.

localname

If supplied, this is the local name inside the ZIP archive that will override the filename.

start

This parameter is not used but is required to extend ZipArchive.

length

This parameter is not used but is required to extend ZipArchive.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.

Przykład #1 Open and extract

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    
$zip->addFile('/path/to/index.txt''newname.txt');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>

Notatki

Informacja:

When a file is set to be added to the archive, PHP will attempt to lock the file and it is only released once the ZIP operation is done. In short, it means you can first delete an added file after the archive is closed.



ZipArchive::addFromString

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::addFromStringAdd a file to a ZIP archive using its contents

Opis

bool ZipArchive::addFromString ( string $localname , string $contents )

Add a file to a ZIP archive using its contents.

Parametry

localname

The name of the entry to create.

contents

The contents to use to create the entry. It is used in a binary safe mode.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Add an entry to a new archive

<?php
$zip 
= new ZipArchive;
$res $zip->open('test.zip'ZipArchive::CREATE);
if (
$res === TRUE) {
    
$zip->addFromString('test.txt''file content goes here');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>

Przykład #2 Add file to a directory inside an archive

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    
$zip->addFromString('dir/test.txt''file content goes here');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>


ZipArchive::close

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::closeClose the active archive (opened or newly created)

Opis

bool ZipArchive::close ( void )

Close opened or created archive and save changes. This method is automatically called at the end of the script.

Parametry

Ta funkcja nie posiada parametrów.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.



ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::deleteIndexdelete an entry in the archive using its index

Opis

bool ZipArchive::deleteIndex ( int $index )

Delete an entry in the archive using its index.

Parametry

index

Index of the entry to delete.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Delete file from archive using its index

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    
$zip->deleteIndex(2);
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>


ZipArchive::deleteName

(PHP 5 >= 5.2.0, PECL zip >= 1.5.0)

ZipArchive::deleteNamedelete an entry in the archive using its name

Opis

bool ZipArchive::deleteName ( string $name )

Delete an entry in the archive using its name.

Parametry

name

Name of the entry to delete.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Deleting a file and directory from an archive, using names

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test1.zip') === TRUE) {
    
$zip->deleteName('testfromfile.php');
    
$zip->deleteName('testDir/');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>


ZipArchive::extractTo

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::extractToExtract the archive contents

Opis

bool ZipArchive::extractTo ( string $destination [, mixed $entries ] )

Extract the complete archive or the given files to the specified destination.

Parametry

destination

Location where to extract the files.

entries

The entries to extract. It accepts either a single entry name or an array of names.

Zwracane wartości

Zwraca TRUE w przypadku powodzenia, FALSE w przypadku błędu.

Przykłady

Przykład #1 Extract all entries

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    
$zip->extractTo('/my/destination/dir/');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>

Przykład #2 Extract two entries

<?php
$zip 
= new ZipArchive;
$res $zip->open('test_im.zip');
if (
$res === TRUE) {
    
$zip->extractTo('/my/destination/dir/', array('pear_item.gif''testfromfile.php'));
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'failed';
}
?>


ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::getArchiveCommentReturns the Zip archive comment

Opis